SpringBoot-Spring Data Jpa - 复杂业务查询 Specification
-
Specification 前言
maven依赖
<!-- Specification封装工具类--><!-- 使用起来更简单,不过是非官方出品,可能会出现版本不兼容的问题--><!-- https://github.com/wenhao/jpa-spec --><dependency><groupId>com.github.wenhao</groupId><artifactId>jpa-spec</artifactId><version>3.2.4</version></dependency>
应对Spring Data Jpa 复杂逻辑查询而生的条件对象
-
Specification 构建对象
- Object泛型描述,针对业务逻辑构建的条件对象,通常与Repository层泛型一直
- and 与 or 就是创建的逻辑 ‘与’、‘或’ 对象,表示构建的条件对象为逻辑 ‘与’、‘或’ 关系
Specification<Object> and = Specifications.and().build();
Specification<Object> or = Specifications.or().build();
-
Specification 编写逻辑语句
- 一般代码结构分为三个部分
- 断言,为 true 则促发当前逻辑
- 实体对象中的属性名称,会根据实体对象直接映射表关系,建议反射写法更好,代码容错性、解耦性更高
- 传入的条件,例子中逻辑语句以 ‘between’ 为例子,必须满足参数 ‘111L’ 与 ‘assembly.getOsVersionId()’ 之间才匹配, ‘between’ 一般用于时间查询,eq 、like 等查询这里均需要一个参数即可,多个条件以数组的形式入参
- like 模糊查询需要更灵活,需要手动指定 ‘%’ 的位置,例子中以前后均模糊匹配为例子
- 一般代码结构分为三个部分
Specification<Assembly> build = Specifications.<Assembly>and().between(null != assembly.getOsVersionId(),"osVersionId", 111L,assembly.getOsVersionId()).build();.findAll(build);---------------------------------------------------------------------------------------Specification<Assembly> build = Specifications.<Assembly>and().like(StringUtils.isNotBlank(assembly.getAssemblyName()),"%assemblyName%",assembly.getAssemblyName()).build();.findAll(build);