SpringDataJPA之Specification复杂查询

前言

继上次SpringData-JPA之ExampleMatcher实例查询使用一会之后发现ExampleMatcher对日期的查询特别糟糕,所以才有了Specification查询的研究。

2018年8月11日:根据所学所用,重新更新了文章,并增加了Pageable分页排序功能。

实现

对应的Repository需要实现JpaSpecificationExecutor接口

public interface EventRepository extends JpaRepository<Event, Integer> , JpaSpecificationExecutor<Event>{

Specification与Controller业务逻辑

    @GetMapping("/event/list")
    public ApiReturnObject findAllEvent(String event,Timestamp registerTime,Integer pageNumber,Integer pageSize) {
        if(pageNumber==null) pageNumber=1;
        if(pageSize==null) pageNumber=10;
        //分页
        //Pageable是接口,PageRequest是接口实现,new PageRequest()是旧方法,PageRequest.of()是新方法
        //PageRequest.of的对象构造函数有多个,page是页数,初始值是0,size是查询结果的条数,后两个参数参考Sort对象的构造方法
        Pageable pageable = PageRequest.of(pageNumber,pageSize,Sort.Direction.DESC,"id");
        //Specification查询构造器
        Specification specification=new Specification() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Predicate condition1 = null;
                if(StringUtils.isNotBlank(eventTitle)) {
                    condition1 = criteriaBuilder.like(root.get("eventTitle"),"%"+eventTitle+"%");
                }else {
                    condition1 = criteriaBuilder.like(root.get("eventTitle"),"%%");
                }
                Predicate condition2 = null;
                if(registerTime!=null) {
                    condition2 = criteriaBuilder.greaterThan(root.get("registerTime"), registerTime);
                }else {
                    condition2 = criteriaBuilder.greaterThan(root.get("registerTime"), new Timestamp(1514736000000L));
                }
                //Predicate conditionX=criteriaBuilder.and(condition1,condition2);
                //query.where(conditionX);
                query.where(condition1,condition2);
                //query.where(getPredicates(condition1,condition2)); //这里可以设置任意条查询条件
                return null;  //这种方式使用JPA的API设置了查询条件,所以不需要再返回查询条件Predicate给Spring Data Jpa,故最后return null
            }
        };
        Page list=eventRepository.findAll(specification, pageable);

        return ApiReturnUtil.page(list);
    }

ApiReturnUtil.page封装

    public static ApiReturnObject page(Page returnObject) {
        return new ApiReturnObject(returnObject.getNumber()+"",returnObject.getNumberOfElements()+"",returnObject.getTotalElements()+"",returnObject.getTotalPages()+"","00","success",returnObject.getContent());  
    }
    String errorCode="00";
    Object errorMessage;
    Object returnObject;
    String pageNumber;
    String pageSize;
    String totalElements;
    String totalPages;

    public ApiReturnObject(String pageNumber,String pageSize,String totalElements,String totalPages,String errorCode, Object errorMessage, Object returnObject) {
        super();
        this.pageNumber = pageNumber;
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.returnObject = returnObject;
        this.pageSize = pageSize;
        this.totalElements = totalElements;
        this.totalPages = totalPages;
    }

返回对象有用的是pageNumber、pageSize、totalElements、totalPages等属性,可对其进行封装

{
    "errorCode": "00",
    "errorMessage": "success",
    "pageNumber": "1",
    "pageSize": "2",
    "returnObject": [
        {
            "eventTitle": "1111",
            "id": 3,
            "registerTime": 1528702813000,
            "status": "0"
        },
        {
            "eventTitle": "小明失踪",
            "id": 2,
            "registerTime": 1526268436000,
            "status": "0"
        }
    ],
    "totalElements": "5",
    "totalPages": "3"
}

可以查询了。网上关于这个的资料也很少。希望可以帮到大家。

可能遇到的错误

Unable to locate Attribute  with the the given name [event] on this ManagedType [org.microservice.tcbj.yytsg.checkcentersys.entity.Event]

出现这样的情况,一般是因为实体类中没有这个属性,例如我Event的是eventTitle,写成了event,就会报错。

你可能感兴趣的:(Spring,SpringBoot2启示录)