Specifications :: Spring Data JPA
- 动态构建相应的查询语句
- 不属于Repository体系,实现了一组JPA criteria 认证
接口方法
- Optional<T> findOne(@Nullable Specification<T> spec);
- List<T> findAll(@Nullable Specification<T> spec);
- Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);
- List<T> findAll(@Nullable Specification<T> spec, Sort sort);
- long count(@Nullable Specification<T> spec);
Specification
@Nullable
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder);
Root接口,代表查询的根对象,可以通过root获取实体中的属性
query :代表一个顶层查询对象,用来自定义查询
cb :用来构建查询,此对象里有很多条件方法
对于JpaSpecificationExecutor,这个接口基本是围绕着Specification接口来定义的。我们可以简单的理解为,Specification构造的就是查询条件。
示例
public interface PersonRepsotory extends
JpaRepository<Person, Integer>,
JpaSpecificationExecutor<Person>, PersonDao {
Specification<Customer> specificationCustomer = (root, query, cb) ->
cb.like(root.get("name"), "%" + "xiaom" + "%");
Pageable pageable = PageRequest.of(1, 10,Sort.by("name"));
Page<Customer> all = curdRepository.findAll(specificationCustomer, pageable);
List<Customer> content = all.getContent();
//获取总页数
int getTotalPages();
//获取总记录数
long getTotalElements();
//获取列表数据
List<T> getContent();
多表查询
Specification<LinkMan> spec = (root, query, cb) -> {
Join<LinkMan, Customer> join = root.join("customer", JoinType.INNER);
return cb.like(join.get("custName").as(String.class),"");
};
linkManDao.findAll(spec);