使用jpa直接操作mysql数据。
引用
<!--数据库--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
pojo
@Entitypublic class Girl {@Id//设置自增,2.0之后要加后面的属性@GeneratedValue(strategy = GenerationType.IDENTITY)private int id;private String cupSize;private int age;public Girl() {}……}
dao层
public interface ICustomerDao extends JpaRepository<Customer,Integer>,JpaSpecificationExecutor<Customer>{}
操作
增加和修改
区别在于有没有主键
Customer customer = new Customer();customer.setCustName("hello Spring data JPA");customerService.save(customer);
删除
customerService.delete(1);
查询
List<Customer> list = customerService.findAll();Customer customer = customerService.findById(1);
命名规则查询
List<Customer> findByCustNameAndCustAddressLike(StringcustName, String custAddress);
自定义JPQL
@Query("from Customer where custName = ?1 and custAddress like ?2")List<Customer> findAll(String custName, String custAddress);@Query("update Customer set custName = ?2,custAddress = ?3 where custId = ?1")@Modifyingvoid update(Integer custId, String custName, StringcustAddress);
自定义sql
@Query(value = "select * from cst_customer where cust_name = ?1 and cust_address like ?2",nativeQuery=true)List<Customer> findAllByNative(String custName, StringcustAddress);
Specification对象查询和分页
//创建Specification对象 select * from cst_customerSpecification<Customer> specification = new Specification() {@Nullable@Override// 此内部方法只是负责拼接条件及参数public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {Predicate predicate = cb.and(cb.equal(root.get("custName"),"京西集团"),cb.like(root.get("custAddress"),"%山%"));return null;}};Pageable pageable = PageRequest.of(1,2);Page<Customer> page = customerService.findAllByPage(specification, pageable);List<Customer> list = page.getContent();
