SpringDataJPA-Specification
使用Specification可以构建动态查询
原生的使用起来有点复杂,这里推介一个别人封装好的工具包
这里是github的地址
https://github.com/wenhao/jpa-spec/blob/master/README_CN.md
<!-- https://mvnrepository.com/artifact/com.github.wenhao/jpa-spec -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.2.4</version>
</dependency>
具体用法
方法 | 含义 |
---|---|
gt/ge | greater than/greater equal ,大于/大于等于 |
lt/le | less than/less equal,小于/小于等于 |
eq/ne | equal/not equal, 等于/不等于 |
in/notIn | 包含/不包含 |
like/notLike | like/notLike |
between | between |
基础查询均支持三个参数或者两个参数的用法
true
(默认),应用此条件查询。不同的查询条件之间可以用and或者or来连接
具体代码使用可参考下面的实例
@Slf4j
@RestController
@RequestMapping("/chapter/seven")
public class ChapterSevenController {
@Autowired
private CatRepository catRepository;
@ApiOperation(value = "and条件查询", httpMethod = "POST")
@PostMapping("/search/cat/and")
public List<CatEntity> searchCatAnd(@RequestBody ChapterSevenDTO chapterSevenDTO) {
Specification<CatEntity> specification = Specifications.<CatEntity>and()
.gt(null != chapterSevenDTO.getAge(), "age", chapterSevenDTO.getAge())
.lt(null != chapterSevenDTO.getHeight(), "height", chapterSevenDTO.getHeight())
.eq(null != chapterSevenDTO.getWeight(), "weight", chapterSevenDTO.getWeight()).build();
return catRepository.findAll(specification);
}
@ApiOperation(value = "or条件查询", httpMethod = "POST")
@PostMapping("/search/cat/or")
public List<CatEntity> searchCatOr(@RequestBody ChapterSevenDTO chapterSevenDTO) {
Specification<CatEntity> specification = Specifications.<CatEntity>or()
.gt(null != chapterSevenDTO.getAge(), "age", chapterSevenDTO.getAge())
.lt(null != chapterSevenDTO.getHeight(), "height", chapterSevenDTO.getHeight())
.eq(null != chapterSevenDTO.getWeight(), "weight", chapterSevenDTO.getWeight()).build();
return catRepository.findAll(specification);
}
@ApiOperation(value = "复杂条件查询", httpMethod = "POST")
@PostMapping("/search/cat")
public List<CatEntity> searchCat(@RequestBody ChapterSevenDTO chapterSevenDTO) {
Specification<CatEntity> specification = Specifications.<CatEntity>or()
.gt(null != chapterSevenDTO.getAge(), "age", chapterSevenDTO.getAge())
.lt(null != chapterSevenDTO.getHeight(), "height", chapterSevenDTO.getHeight()).build();
Specification<CatEntity> specification1 = Specifications.<CatEntity>and()
.eq(null != chapterSevenDTO.getSex(), "sex", chapterSevenDTO.getSex())
.eq(null != chapterSevenDTO.getName(), "name", chapterSevenDTO.getName()).build();
Specification<CatEntity> specification2 = Specifications.<CatEntity>and().predicate(specification).predicate(specification1)
.lt(null != chapterSevenDTO.getWeight(), "weight", chapterSevenDTO.getWeight()).build();
return catRepository.findAll(specification2);
}
}