前言
Jpa的多条件查询,肯定会想到继承JpaSpecificationExecutor<T>
多条件查询如何实现呢,进入JpaSpecificationExecutor中有这样的一个方法
Page<T> findAll(@Nullable Specification<T> var1, Pageable var2);
只需构建一个Specification,就能实现多条件分页查询
提示:以下是本篇文章正文内容,下面案例可供参考
Repository
public interface UserJpa extends JpaRepositoryImplementation<User, Integer> {
}
Service
public Page<User> listNews(Pageable pageable,User user) {
return userJpa.findAll((Specification<User>) (root, cq, cb) -> {
// root 数据库中的字段名
// cq 构建查询条件
// cb 执行查询条件
// 1. 创建集合 存储查询条件
List<Predicate> list = new ArrayList<>();
// 2. 添加查询条件
if (!"".equals(user.getName()) && user.getName() != null) {
// 当name有值时 项目list集合中存储查询条件 select * from user where name like %张%
list.add(cb.like(root.<String>get("name"), "%" + name + "%"));
}
if (!"".equals(user.getSex()) && user.getSex() != null) {
// 当sex有值时 项目list集合中存储查询条件 select * from user where sex = "男"
list.add(cb.equal(root.<String>get("sex"),sex));
}
// 3. 执行查询
cq.where(list.toArray(new Predicate[list.size()]));
return null;
},pageable);
}
Controller
/**
* page 默认是0页
* size 默认每页显示5条
* sort 根据id倒序查询
*/
@RequestMapping("/listNews")
public Page<User> listNews(@PageableDefault(page = 0,size = 5,sort = {"id"},direction = Sort.Direction.DESC)
Pageable pageable,User user){
return userService.listNews(pageable,user);
}
声明:本博客如无特殊说明皆为原创,转载请注明来源:Spring Jpa Data多条件分页查询,谢谢!