1. 程式人生 > >SpringDataJpa基礎篇4:JpaSpecificationExecutor多條件查詢

SpringDataJpa基礎篇4:JpaSpecificationExecutor多條件查詢

 

2、實戰應用

這裡就以部門表為例子進行多條件查詢分頁

2.1、實體類及工具類

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
/**
 * @ClassName Dept
 * @描述
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="sys_dept")
public class Dept implements Serializable {
    @Id
    private  Long id;
    private String name;
    @Column(name="pid")
    private Long pid;//父部門id
    @Column(name="pids")
    private String pids;//所有上級部門,如[[0],[26],]寫法
    @Column(name="order_num")
    private Integer orderNum; //排序
    private Integer state;//狀態
    private String remarks;//部門描述

}

【工具類】

import java.util.List;

/**
 * 分頁返回結果
 * @param <T>
 */
public class PageResult<T> {
    private long total;//總條數
    private List<T> rows;//返回的資料集
    public PageResult() {
    }
    public PageResult(long total, List<T> rows) {
        this.total = total;
        this.rows = rows;
    }
    public long getTotal() {
        return total;
    }
    public void setTotal(long total) {
        this.total = total;
    }
    public List<T> getRows() {
        return rows;
    }
    public void setRows(List<T> rows) {
        this.rows = rows;
    }
    @Override
    public String toString() {
        return "PageResult{" +
                "total=" + total +
                ", rows=" + rows +
                '}';
    }
}

 

2.2、dao層

/**
 * @ClassName DeptDao
 * @描述 繼承JpaSpecificationExecutor實現多條件查詢 
 **/
public interface DeptDao extends JpaRepository<Dept,Long>, JpaSpecificationExecutor<Dept> {

}

2.3、service層

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @ClassName DeptService
 **/
@Service
public class DeptService {
    @Autowired
    private DeptDao deptDao;
//分頁查詢
public Page<Dept> queryPage(int page, int size, Map whereMap){
        Specification<Dept> specification = createWhere(whereMap);
        PageRequest pageRequest=PageRequest.of(page-1,size);
      return   deptDao.findAll(specification,pageRequest);
    }

    /**
     * 動態構建查詢條件
     * @param searchMap
     */
    private Specification<Dept> createWhere(Map searchMap){

       return new Specification<Dept>() {
           @Override
           public Predicate toPredicate(Root<Dept> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
               List<Predicate> predicateList = new ArrayList<Predicate>();
               System.err.println("*********id:"+searchMap.get("id"));
               //id
               if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                   predicateList.add(cb.equal(root.get("id").as(Long.class),(Long)searchMap.get("id")));
               }
               System.err.println("***name:"+searchMap.get("name"));
               //name
               if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                   predicateList.add(cb.like(root.get("name").as(String.class),"%"+(String)searchMap.get("name")+"%"));
               }
               //注意cb.or表示兩個查詢條件之間是or;cb.and表示查詢條件之間是and關係
               return cb.or(predicateList.toArray(new Predicate[predicateList.size()]));
           }
       };
    }
}

2.4、測試程式碼

import cn.wzy.yw.common.PageResult;
import cn.wzy.yw.entity.Dept;
import cn.wzy.yw.service.DeptService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import cn.wzy.yw.common.Result;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
@RunWith(SpringRunner.class)
@SpringBootTest
public class YwApplicationTests {
    @Autowired
    private DeptService deptService;
    @Autowired
    private IdWorker idWorker;
    @Test
    public void contextLoads() {
    }   
    @Test
    public void test3(){
        HashMap map=new HashMap();
        map.put("id",1073478326892498945L);
        map.put("name","公司");
        Page<Dept> deptList = deptService.queryPage(1, 2, map);
        PageResult<Dept> pageInfo = new PageResult<>(deptList.getTotalElements(), deptList.getContent());
        System.out.println("****"+ pageInfo.toString());
    }
}