目录
ORM框架,会大大减少重复性代码,开发速度快;
底层使用了hibernate;
和原生一样
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);
System.out.println(customer);
/**
* 根据方法的命名规则查询
* 拓展:
* 约定大于配置(很重要的思想)
* @param custName
* @param custAddress
* @return
*/
List<Customer> findByCustNameAndCustAddressLike(StringcustName, String custAddress);
/**
* 查询集合(带条件--JPQL)
* @param custName
* @param custAddress
* @return
*/
@Query("from Customer where custName = ?1 and custAddress like ?2")
List<Customer> findAll(String custName, String custAddress);
/**
* Sql
* @param custName
* @param custAddress
* @return
*/
@Query(value = "select * from cst_customer where cust_name = ?1 and cust_address like ?2",nativeQuery=true)
List<Customer> findAllByNative(String custName, StringcustAddress);
/**
* 自定更新
* @param custId
* @param custName
* @param custAddress
*/
@Query("update Customer set custName = ?2,custAddress = ?3 where custId = ?1")
@Modifying
void update(Integer custId, String custName, StringcustAddress);
方便拼接查询条件
查询
//创建Specification对象 select * from cst_customer where
Specification<Customer> specification = new Specification<Customer>() {
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
// 条件
Predicate p1 = criteriaBuilder.equal(root.get("custName"), "客户2");
Predicate p2 = criteriaBuilder.like(root.get("custAddress"), "%北%");
return criteriaBuilder.and(p1,p2);
}
};
List<Customer> all = service.findAll(specification);
分页
传入参数第几页,多少条!
//创建Specification对象 select * from cst_customer
Specification<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();
必须用立即加载
原文:https://www.cnblogs.com/birdofparadise/p/10012287.html