Spring Data JPA03 JpaSpecificationExecutor

Specifications :: Spring Data JPA

  1. 动态构建相应的查询语句
  2. 不属于Repository体系,实现了一组JPA criteria  认证

接口方法

  1. Optional<T> findOne(@Nullable Specification<T> spec);
  2. List<T> findAll(@Nullable Specification<T> spec);
  3. Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);
  4. List<T> findAll(@Nullable Specification<T> spec, Sort sort);
  5. 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);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值