使用jpa直接操作mysql数据。

引用

  1. <!--数据库-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. </dependency>

pojo

  1. @Entity
  2. public class Girl {
  3. @Id
  4. //设置自增,2.0之后要加后面的属性
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private int id;
  7. private String cupSize;
  8. private int age;
  9. public Girl() {
  10. }
  11. ……
  12. }

dao层

  1. public interface ICustomerDao extends JpaRepository<Customer,Integer>,JpaSpecificationExecutor<Customer>{
  2. }

操作

增加和修改

区别在于有没有主键

  1. Customer customer = new Customer();
  2. customer.setCustName("hello Spring data JPA");
  3. customerService.save(customer);

删除

  1. customerService.delete(1);

查询

  1. List<Customer> list = customerService.findAll();
  2. Customer customer = customerService.findById(1);

命名规则查询

  1. List<Customer> findByCustNameAndCustAddressLike(StringcustName, String custAddress);

自定义JPQL

  1. @Query("from Customer where custName = ?1 and custAddress like ?2")
  2. List<Customer> findAll(String custName, String custAddress);
  3. @Query("update Customer set custName = ?2,custAddress = ?3 where custId = ?1")
  4. @Modifying
  5. void update(Integer custId, String custName, StringcustAddress);

自定义sql

  1. @Query(value = "select * from cst_customer where cust_name = ?1 and cust_address like ?2",nativeQuery=true)
  2. List<Customer> findAllByNative(String custName, StringcustAddress);

Specification对象查询和分页

  1. //创建Specification对象 select * from cst_customer
  2. Specification<Customer> specification = new Specification() {
  3. @Nullable
  4. @Override
  5. // 此内部方法只是负责拼接条件及参数
  6. public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
  7. Predicate predicate = cb.and(cb.equal(root.get("custName"),"京西集团"),
  8. cb.like(root.get("custAddress"),"%山%"));
  9. return null;
  10. }
  11. };
  12. Pageable pageable = PageRequest.of(1,2);
  13. Page<Customer> page = customerService.findAllByPage(specification, pageable);
  14. List<Customer> list = page.getContent();