当Repository接口继承了JpaSpecificationExecutor后,我们就可以使用如下接口进行分页查询:

    /**
* Returns a {@link Page} of entities matching the given {@link Specification}.
*
* @param spec can be {@literal null}.
* @param pageable must not be {@literal null}.
* @return never {@literal null}.
*/
Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);

结合jpa-spec可以很容易构造出Specification:

jpa-spec github地址:https://github.com/wenhao/jpa-spec

public Page<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.eq(StringUtils.isNotBlank(request.getName()), "name", request.getName())
.gt(Objects.nonNull(request.getAge()), "age", 18)
.between("birthday", new Date(), new Date())
.like("nickName", "%og%", "%me")
.build(); return personRepository.findAll(specification, new PageRequest(0, 15));
}

单表查询确实很简单,但对复杂查询,就复杂上些了:

public List<Phone> findAll(SearchRequest request) {
Specification<Phone> specification = Specifications.<Phone>and()
.eq(StringUtils.isNotBlank(request.getBrand()), "brand", "HuaWei")
.eq(StringUtils.isNotBlank(request.getPersonName()), "person.name", "Jack")
.build(); return phoneRepository.findAll(specification);
}

这里主表是phone,使用了person的name做条件,使用方法是person.name。

jpa-spec内部会分析person.name,如下代码:

public From getRoot(String property, Root<T> root) {
if (property.contains(".")) {
String joinProperty = StringUtils.split(property, ".")[0];
return root.join(joinProperty, JoinType.LEFT);
} else {
return root;
}
}

就可看到它用了root.join,那就有一个问题,如果有两个person字段的条件,那就要再join一次,就会生成这样的sql:

select * from phone left outer join person on XX=XX left outer join person XX=XX.

这样肯定不满足需求。这应该也是jpa-spec的一个bug吧

为了解决这个问题,可以使用它提供的另一种方式查询:

public List<Phone> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.between("age", 10, 35)
.predicate(StringUtils.isNotBlank(jack.getName()), ((root, query, cb) -> {
Join address = root.join("addresses", JoinType.LEFT);
return cb.equal(address.get("street"), "Chengdu");
}))
.build(); return phoneRepository.findAll(specification);
}

这要就可以解决大多数情况了,除了分页

看下正常的单表分页+排序查询:

public Page<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.eq(StringUtils.isNotBlank(request.getName()), "name", request.getName())
.gt("age", 18)
.between("birthday", new Date(), new Date())
.like("nickName", "%og%")
.build(); Sort sort = Sorts.builder()
.desc(StringUtils.isNotBlank(request.getName()), "name")
.asc("birthday")
.build(); return personRepository.findAll(specification, new PageRequest(0, 15, sort));
}

如果在此基础上增加关联,如下代码:

public Page<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.predicate(StringUtils.isNotBlank(jack.getName()), ((root, query, cb) -> {
Join address = root.join("addresses", JoinType.LEFT);
return cb.equal(address.get("street"), "Chengdu");
}))
.eq(StringUtils.isNotBlank(request.getName()), "name", request.getName())
.gt("age", 18)
.between("birthday", new Date(), new Date())
.like("nickName", "%og%")
.build(); Sort sort = Sorts.builder()
.desc(StringUtils.isNotBlank(request.getName()), "name")
.asc("birthday")
.build(); return personRepository.findAll(specification, new PageRequest(0, 15, sort));
}

就会发现addresses的延迟加载失效,生成很多查询addresses的语句,解决方案如下:

public Page<Person> findAll(SearchRequest request) {
Specification<Person> specification = Specifications.<Person>and()
.predicate(StringUtils.isNotBlank(jack.getName()), ((root, query, cb) -> {
Join address;
if (Long.class != query.getResultType()) {
address = (Join) root.fetch("addresses", JoinType.LEFT);
} else {
address = root.join("addresses", JoinType.LEFT);
}
return cb.equal(address.get("street"), "Chengdu");
}))
.eq(StringUtils.isNotBlank(request.getName()), "name", request.getName())
.gt("age", 18)
.between("birthday", new Date(), new Date())
.like("nickName", "%og%")
.build(); Sort sort = Sorts.builder()
.desc(StringUtils.isNotBlank(request.getName()), "name")
.asc("birthday")
.build(); return personRepository.findAll(specification, new PageRequest(0, 15, sort));
}

至此,用Specification查询就应该够用了,再配合JpaRepository (SimpleJpaRepository)提供的方法 和@Query注解方法,和criteria api查询,这四种JPA查询就可以解决大多数应用问题了。

spring data jpa Specification 复杂查询+分页查询的更多相关文章

  1. SpringBoot中使用Spring Data Jpa 实现简单的动态查询的两种方法

    软件152 尹以操 首先谢谢大佬的简书文章:http://www.jianshu.com/p/45ad65690e33# 这篇文章中讲的是spring中使用spring data jpa,使用了xml ...

  2. spring data jpa 使用方法命名规则查询

    按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写.框架在进行方法名解析时,会先把方法名多余的前缀 ...

  3. 【hql】spring data jpa中 @Query使用hql查询 问题

    spring data jpa中 @Query使用hql查询 问题 使用hql查询, 1.from后面跟的是实体类 不是数据表名 2.字段应该用实体类中的字段 而不是数据表中的属性 实体如下 hql使 ...

  4. Spring Data JPA 复杂/多条件组合查询

    1: 编写DAO类或接口  dao类/接口 需继承 public interface JpaSpecificationExecutor<T> 接口: 如果需要分页,还可继承 public ...

  5. Spring Data JPA 实现多表关联查询

    本文地址:https://liuyanzhao.com/6978.html 最近抽出时间来做博客,数据库操作使用的是 JPA,相对比 Mybatis 而言,JPA 单表操作非常方便,增删改查都已经写好 ...

  6. spring data jpa 使用JPQL的方式查询

    用Spring Data JPA提供的查询方法已经可以解决大部分的应用场景,但是对于某些业务来说,我们还需要灵活的构造查询条件,这时就可以使用@Query注解,结合JPQL的语句方式完成查询 @Que ...

  7. spring data jpa Specification动态查询

    package com.ytkj.entity; import javax.persistence.*; import java.io.Serializable; /** * @Entity * 作用 ...

  8. 【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现

    一.不带有动态条件的查询 分页的实现 实例代码: controller:返回的是Page<>对象 @Controller @RequestMapping(value = "/eg ...

  9. Spring data JPA先排序再分页。

    //工具类,增删改查等等package com.yunqing.service.impl; import java.util.Map; import org.springframework.beans ...

随机推荐

  1. PCL智能指针疑云 <三> 智能指针作为函数的传值参数和传引用参数

    一 函数的参数传递可以简单分类为“传值”和“传引用”. 声明函数时,形参带引用“&”,则函数调用时,是把实参所在的内存直接传给函数所开辟的栈内存.在函数内对形参的修改相当于对实参也进行修改. ...

  2. HDU 1711 Number Sequence(KMP)附带KMP的详解

    题目代号:HDU 1711 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711 Number Sequence Time Limit: 10000/ ...

  3. HDU1022--Train Problem I(栈的应用)

    Problem Description As the new term comes, the Ignatius Train Station is very busy nowadays. A lot o ...

  4. 一个强大的json解析工具类

    该工具类利用递归原理,能够将任意结构的json字符串进行解析.当然,如果需要解析为对应的实体对象时,就不能用了 package com.wot.cloudsensing.carrotfarm.util ...

  5. CentOS 7 安装wps2019

    1. download https://www.wps.cn/product/wpslinux 2. rpm 安装缺少lib包,于是yum 安装 .x86_64.rpm 3.安装完成,运行的时候又报错 ...

  6. springboot上传文件大小限制的配置

    springboot配置文件: application.properties #配置文件传输 spring.servlet.multipart.enabled =true spring.servlet ...

  7. Ping链路测试

    https://help.aliyun.com/knowledge_detail/40573.html?spm=5176.2020520165.121.d519.4b4f7029sHzfmi#TRAC ...

  8. ES6 暂时性死区

    在ES6中,声明变量新增了两个关键字:let命令和const命令 如果在区块中存在let或者const命令时,任何变量都必须在声明之前使用,无论是区块外部的全局变量或者是区块内部的变量: /* 区块外 ...

  9. kafka window安装与配置

    一.安装jdk1.8(此处省略) 二.安装zookeeper1. 下载安装包:http://zookeeper.apache.org/releases.html,解压到指定目录(如下) 2. 在系统变 ...

  10. (转)使用NMAP工具扫描端口

    原文:http://www.linuxde.net/2013/02/12354.html nmap 是一个用于网络探索或安全评测的工具.它支持 ping 扫描(判定哪些主机在运行),多端口扫描技术(判 ...