欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring data jpa的使用与详解(复杂动态查询及分页,排序)

程序员文章站 2022-08-07 22:38:45
一、 使用specification实现复杂查询(1) 什么是specificationspecification是springdatejpa中的一个接口,他是用于当jpa的一些基本crud操作的扩展...

一、 使用specification实现复杂查询

(1) 什么是specification

specification是springdatejpa中的一个接口,他是用于当jpa的一些基本crud操作的扩展,可以把他理解成一个spring jpa的复杂查询接口。其次我们需要了解criteria 查询,这是是一种类型安全和更面向对象的查询。而spring data jpa支持jpa2.0的criteria查询,相应的接口是jpaspecificationexecutor。

而jpaspecificationexecutor这个接口基本是围绕着specification接口来定义的,specification接口中只定义了如下一个方法:

predicate topredicate(root<t> root, criteriaquery<?> query, criteriabuilder cb); 

criteria查询基本概念:

criteria 查询是以元模型的概念为基础的,元模型是为具体持久化单元的受管实体定义的,这些实体可以是实体类,嵌入类或者映射的父类。

criteriaquery接口:

代表一个specific的顶层查询对象,它包含着查询的各个部分,比如:select 、from、where、group by、order by等注意:criteriaquery对象只对实体类型或嵌入式类型的criteria查询起作用。

root:

代表criteria查询的根对象,criteria查询的查询根定义了实体类型,能为将来导航获得想要的结果,它与sql查询中的from子句类似。
root实例是类型化的,且定义了查询的from子句中能够出现的类型。root代表查询的实体类,query可以从中得到root对象,告诉jpa查询哪一个实体类,还可以添加查询条件,还可以结合entitymanager对象 得到最终查询的 typedquery对象。

criteriabuilder接口:

用来构建critiaquery的构建器对象predicate:一个简单或复杂的谓词类型,其实就相当于条件或者是条件组合。 可通过 entitymanager.getcriteriabuilder 而得。

二、使用specification进行复杂的动态查询

maven的依赖继续使用上一章的就可以,这里修改一下实体类和controller层。

请求实体类:

@data
public class accountrequest {

  //从第几页开始
  private integer page;

  //每一页查询多少
  private integer limit;

  private string id;

  private string name;

  private string pwd;

  private string email;

  private integer[] types;

}

实体类:

@data
@entity
@table(name = "account")
@tostring
@entitylisteners(auditingentitylistener.class)
public class account {

  @id
  @genericgenerator(name = "idgenerator", strategy = "uuid")
  @generatedvalue(generator = "idgenerator")
  private string id;

  @column(name = "username", unique = true, nullable = false, length = 64)
  private string username;

  @column(name = "password", nullable = false, length = 64)
  private string password;

  @column(name = "email", length = 64)
  private string email;

  @column(name = "type")
  private short type;

  @createddate
  @column(name = "create_time", nullable = false)
  private localdatetime createtime;

}

repository层:

public interface accountrepository extends jparepository<account,string>, jpaspecificationexecutor<account> {}

controller层(还是直接略过service层)

@autowired
  private accountrepository repository;


  @postmapping("/get")
  public list<account> get(@requestbody accountrequest request){
    specification<account> specification = new specification<account>() {

      @override
      public predicate topredicate(root<account> root, criteriaquery<?> criteriaquery, criteriabuilder builder) {
        //所有的断言 及条件
        list<predicate> predicates = new arraylist<>();
        //精确匹配id pwd
        if (request.getid() != null) {
          predicates.add(builder.equal(root.get("id"), request.getid()));
        }
        if (request.getpwd() != null) {
          predicates.add(builder.equal(root.get("password"), request.getpwd()));
        }
        //模糊搜索 name
        if (request.getname() != null && !request.getname().equals("")) {
          predicates.add(builder.like(root.get("username"), "%" + request.getname() + "%"));
        }
        if (request.getemail() != null && !request.getemail().equals("")) {
          predicates.add(builder.like(root.get("email"), "%" + request.getemail() + "%"));
        }
        //in范围查询
        if (request.gettypes() != null) {
          criteriabuilder.in<object> types = builder.in(root.get("type"));
          for (integer type : request.gettypes()) {
            types = types.value(type);
          }
          predicates.add(types);
        }
        return builder.and(predicates.toarray(new predicate[predicates.size()]));
      }
    };
    list<account> accounts = repository.findall(specification);

    return accounts;
  }

通过重写specification的topredicate的方法,这样一个复杂的动态sql查询就完成了,通过post请求直接就可以调用了。

三、分页及排序

@postmapping("/page")
  public list<account> getpage(@requestbody accountrequest request){

    specification<account> specification = new specification<account>() {
      @override
      public predicate topredicate(root<account> root, criteriaquery<?> criteriaquery, criteriabuilder criteriabuilder) {
        list<predicate> predicates = new arraylist<>();
        //do anything
        return criteriabuilder.and(predicates.toarray(new predicate[predicates.size()]));
      }
    };
    //表示通过createtime进行 asc排序
    pagerequest page = new pagerequest(request.getpage() - 1, request.getlimit(), sort.direction.asc, "createtime");
    page<account> pageinfo = repository.findall(specification, page);

    return pageinfo.getcontent();
  }

上面的代码是在经过复杂查询并进行分页与排序,通过pagerequest来构建分页排序的规则。传入起始页及每页的数量,还有排序的规则及以哪个属性排序。jpa中是以第0页开始的,所以传参的时候需要注意!

当然,如果你不需要进行复杂的查询也可以对数据进行分页及排序查询。

修改repository,使其继承pagingandsortingrepository。

@repository
public interface accountrepository extends jparepository<account,string>, jpaspecificationexecutor<account> , pagingandsortingrepository<account,string> {
  page<account> findbyage(int age, pageable pageable);
}

使用时先创建pageable参数,然后传进去就可以了。

//显示第1页每页显示3条
pagerequest pr = new pagerequest(1,3);
//根据年龄进行查询
page<account> stus = accountpagerepository.findbyage(22,pr); 
 

排序也是一样的,在repository中创建方法

list<account> findbypwd(string pwd, sort sort);

调用的时候传入sort对象

//设置排序方式为username降序
list<account> accs = accountpagerepository.findbyage("123456",new sort(sort.direction.desc,"username"));
//设置排序以username和type进行升序
acc = accountpagerepository.findbyage("123456",new sort(sort.direction.asc,"username","type"));
//设置排序方式以name升序,以address降序
sort sort = new sort(new sort.order(sort.direction.asc,"name"),new sort.order(sort.direction.desc,"type"));
accs = accountpagerepository.findbyage("123456",sort);

到此这篇关于spring data jpa的使用与详解(复杂动态查询及分页,排序)的文章就介绍到这了,更多相关spring data jpa内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Spring data jpa