Spring Data Jpa之高级查询(jpa-spec插件)

友情链接:Spring Data Jpa的动态查询库 https://github.com/wenhao/jpa-spec

功能介绍

  1. 兼容Spring Data Jpa 和JPA2.1接口。
  2. Equal/NotEqual/Like/NotLike/In/NotIn支持可变参数, Equal/NotEqual 支持空(Null)值。
  3. 每个条件支持关联查询。
  4. 支持自定义条件查询。
  5. 条件构建器。
  6. 支持分页和排序。

导包:

<dependency>
  <groupId>com.github.wenhao</groupId>
  <artifactId>jpa-spec</artifactId>
  <version>3.1.1</version>
  <!-- 把所有依赖都过滤 -->
  <exclusions>
    <exclusion>
      <groupId>*</groupId>
      <artifactId>*</artifactId>
    </exclusion>
  </exclusions>
</dependency>

详细的使用文档:

https://github.com/wenhao/jpa-spec/blob/master/docs/3.1.0_cn.md

https://www.w3cschool.cn/jpaspec/

思路分析:

1 用户传的数据有0-n个

2 所以要准备一个对象接收用户传过来的数据==》Query对象

3 分页的条件对我们来说也是封装到Query对象中的

Query对象(抽个父类):

public abstract class BaseQuery {
    private int currentPage=1;
    private int currentSize=10;
    private boolean sort = true;
    private String sortByColumn;
    //写成抽象类,子类必须实现
    public abstract Specification getSpecification();
    //分页加排序
    public Pageable getPageable(){
        Pageable pageRequest =new PageRequest(currentPage, currentSize);
        if (sortByColumn!=null&&!"".equals(sortByColumn)){
            if (sort){
                Sort sort = new Sort(Sort.Direction.ASC,sortByColumn);
                pageRequest = new PageRequest(currentPage, currentSize,sort);
                return pageRequest;
            }
            Sort sort = new Sort(Sort.Direction.DESC,sortByColumn);
            pageRequest = new PageRequest(currentPage, currentSize,sort);
            return pageRequest;
        }
        return pageRequest;
    }
    //拿到排序
    public Sort getSort(){
        if (sortByColumn!=null&&!"".equals(sortByColumn)){
            if (sort){
                Sort sort = new Sort(Sort.Direction.ASC,sortByColumn);
                return sort;
            }
            Sort sort = new Sort(Sort.Direction.DESC,sortByColumn);
            return sort;
        }
        return null;
    }
    提供相应的getter,setter
}

具体的query对象(以员工查询为例):

public class EmployeeQuery extends BaseQuery{
    private String username;
    private String email;
    private Integer age;
    private Long departmentId;
    @Override
    public Specification getSpecification() {
        Specification<Employee> spec = Specifications.<Employee>and()
                .like(StringUtils.isNotBlank(username),"username", "%"+username+"%")
                .like(StringUtils.isNotBlank(email),"email", "%"+email+"%")
                .ge(age !=null,"age",age)
                .eq(departmentId!=null,"departmentId.id",departmentId)
                .build();
        return spec;
    }
    getter,setter
}    

 

posted @ 2019-03-27 22:57  三只小菜鸟  阅读(3989)  评论(0编辑  收藏  举报