1. 程式人生 > >SpringBoot 條件查詢+分頁

SpringBoot 條件查詢+分頁

最近自己擼了一個web專案,後端用的spring boot,總體來講spring boot的開發效率很高。

今天分享一下條件查詢+分頁返回結果的部分:

spring boot版本:2.0.2

實體類:Device.java

controller中主體:

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;

@PostMapping("/query")
Page<Device> findByFilter(@RequestBody QueryDeviceFilter filter) {
	   	
	Specification<Device> spec = buildFilters(filter);
        PageRequest req = 
        PageRequest.of(filter.getPage(), filter.getSize(), Sort.by(Order.asc("no"))); 
    //按照編號欄位排序
	Page<Device> pageDevice = repo.findAll(spec, req);
	return pageDevice;
}

組織查詢條件:

/** 組織查詢條件 */
public Specification<Device> buildFilters(QueryDeviceFilter filter) {
		
	return new Specification<Device>() {
	@Override
	public Predicate toPredicate(Root<Device> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
		List<Predicate> predicate = new ArrayList<>();
               
        if(filter.getDeployStartTime() != null){
                    predicate.add(cb.greaterThanOrEqualTo(root.get("deployTime").as(Date.class), filter.getDeployStartTime()));
        }
        if(filter.getDeployEndTime() != null){
                    predicate.add(cb.lessThanOrEqualTo(root.get("deployTime").as(Date.class), filter.getDeployEndTime()));
        }
                
        Predicate[] pre = new Predicate[predicate.size()];
        return query.where(predicate.toArray(pre)).getRestriction();
	}
};
}

查詢條件類 QueryDeviceFilter:

public class QueryDeviceFilter {
	String name;
	String no;
	Date deployStartTime;
	Date deployEndTime;
	
	Integer page; //第幾頁
	Integer size; //每頁幾個資料
	
	//...
}

請求:

返回:

{
    "content": [
        {
            "id": 14,
            "no": "0188",
            "name": "汽渡7號機",
            "deployTime": "2017-04-12"
        },
        {
            "id": 11,
            "no": "1888",
            "name": "Alibaba",
            "deployTime": "2017-08-30"
        }
    ],
    "pageable": {
        "sort": {
            "sorted": true,
            "unsorted": false
        },
        "offset": 0,
        "pageSize": 2,
        "pageNumber": 0,
        "paged": true,
        "unpaged": false
    },
    "last": true,
    "totalPages": 1,
    "totalElements": 2,
    "number": 0,
    "size": 2,
    "sort": {
        "sorted": true,
        "unsorted": false
    },
    "first": true,
    "numberOfElements": 2
}