SpringDataJPA笔记(7)-Specification

SpringDataJPA-Specification

使用Specification可以构建动态查询

原生的使用起来有点复杂,这里推介一个别人封装好的工具包

这里是github的地址

https://github.com/wenhao/jpa-spec/blob/master/README_CN.md



    com.github.wenhao
    jpa-spec
    3.2.4

具体用法

方法 含义
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

基础查询均支持三个参数或者两个参数的用法

  1. condition: 如果为true(默认),应用此条件查询。
  2. property: 字段名称。
  3. values: 具体查询的值,eq/ne/like 支持多个值。

不同的查询条件之间可以用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 searchCatAnd(@RequestBody ChapterSevenDTO chapterSevenDTO) {
        Specification specification = Specifications.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 searchCatOr(@RequestBody ChapterSevenDTO chapterSevenDTO) {
        Specification specification = Specifications.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 searchCat(@RequestBody ChapterSevenDTO chapterSevenDTO) {
        Specification specification = Specifications.or()
                .gt(null != chapterSevenDTO.getAge(), "age", chapterSevenDTO.getAge())
                .lt(null != chapterSevenDTO.getHeight(), "height", chapterSevenDTO.getHeight()).build();
        Specification specification1 = Specifications.and()
                .eq(null != chapterSevenDTO.getSex(), "sex", chapterSevenDTO.getSex())
                .eq(null != chapterSevenDTO.getName(), "name", chapterSevenDTO.getName()).build();
        Specification specification2 = Specifications.and().predicate(specification).predicate(specification1)
                .lt(null != chapterSevenDTO.getWeight(), "weight", chapterSevenDTO.getWeight()).build();

        return catRepository.findAll(specification2);
    }
}

源码参考 GITHUB
欢迎关注微信交流
在这里插入图片描述

你可能感兴趣的:(springboot,jpa)