jpa 的 Specification案例

dao接口除了extends JpaRepository外,还要 extends JpaSpecificationExecutor
        <dependency>
            <groupId>com.github.wenhao</groupId>
            <artifactId>jpa-spec</artifactId>
            <version>3.2.4</version>
        </dependency>

 



public interface UserDao extends JpaRepository<User, String>, JpaSpecificationExecutor<User> {

public Page<User> page(QueryVo queryVo){
int page= paging.getPage();
int size= paging.getSize();

//写法一
Specification<User> specification = (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicateList = new ArrayList<>();
if(queryVo.getName!= null && !"".equals(queryVo.getName.trim())){
predicateList.add(criteriaBuilder.like(root.get("userName"), "%"+queryVo.getName+"%"));
}
predicateList.add(criteriaBuilder.equal(root.get("isDelete"), 0));
return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
};

// 写法二
Specification<User> specification2 = new Specification<PerfCase>() {
@Override
public Predicate toPredicate(Root<PerfCase> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
if (queryVo.getName != null && !"".equals(queryVo.getName.trim())) {
predicates.add(criteriaBuilder.like(root.get("perfCaseName"), "%" + queryVo.getName + "%"));
}
predicates.add(criteriaBuilder.equal(root.get("isDelete"), 0));
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};


//排序
Sort.Order order = new Sort.Order(Sort.Direction.DESC, "createTime");
Sort sort = Sort.by(order);

// 构造分页参数
Pageable pageable = PageRequest.of(page-1, size, sort);
Page<User> userPage = userDao.findAll(specification, pageable);
return userPage;
}

}
 

 



posted on 2023-11-14 09:38  wuyicode  阅读(26)  评论(0编辑  收藏  举报