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 
 */
public class PageResult {
    private long total;//总条数
    private List rows;//返回的数据集
    public PageResult() {
    }
    public PageResult(long total, List rows) {
        this.total = total;
        this.rows = rows;
    }
    public long getTotal() {
        return total;
    }
    public void setTotal(long total) {
        this.total = total;
    }
    public List getRows() {
        return rows;
    }
    public void setRows(List 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, JpaSpecificationExecutor {

}

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 queryPage(int page, int size, Map whereMap){
        Specification specification = createWhere(whereMap);
        PageRequest pageRequest=PageRequest.of(page-1,size);
      return   deptDao.findAll(specification,pageRequest);
    }

    /**
     * 动态构建查询条件
     * @param searchMap
     */
    private Specification createWhere(Map searchMap){

       return new Specification() {
           @Override
           public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
               List predicateList = new ArrayList();
               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 deptList = deptService.queryPage(1, 2, map);
        PageResult pageInfo = new PageResult<>(deptList.getTotalElements(), deptList.getContent());
        System.out.println("****"+ pageInfo.toString());
    }
}

 

你可能感兴趣的:(SpringDataJpa)