spring jpa : 多条件查询

Posted 刘晓明

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring jpa : 多条件查询相关的知识,希望对你有一定的参考价值。

方式一:

第一步:EmpAccNumService
package com.payease.scfordermis.service;

import com.payease.scfordermis.bo.ResultBo;
import com.payease.scfordermis.bo.requestBo.ReqEmpAccNumBean;

/**
 * @Created By liuxiaoming
 * @CreateTime 2018/1/15 下午1:55
 **/
public interface EmpAccNumService {

    ResultBo getEmpAccNumList(ReqEmpAccNumBean reqEmpAccNumBean);

}

第二步:EmpAccNumServiceImpl

package com.payease.scfordermis.service.impl;

import com.payease.scfordermis.bo.ResultBo;
import com.payease.scfordermis.bo.requestBo.ReqEmpAccNumBean;
import com.payease.scfordermis.bo.responseBo.PageResponseCommBean;
import com.payease.scfordermis.bo.responseBo.RespEmpAccNumBean;
import com.payease.scfordermis.dao.DepartmentInfoDao;
import com.payease.scfordermis.dao.EmployeeInfoDao;
import com.payease.scfordermis.entity.TDepartmentInfoEntity;
import com.payease.scfordermis.entity.TEmployeeInfoEntity;
import com.payease.scfordermis.service.EmpAccNumService;
import com.payease.scfordermis.utils.MapUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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;

/**
 * @Created By liuxiaoming
 * @CreateTime 2018/1/15 下午1:55
 **/
@Service
public class EmpAccNumServiceImpl implements EmpAccNumService {

    @Autowired
    EmployeeInfoDao employeeInfoDao;
    @Autowired
    DepartmentInfoDao departmentInfoDao;


    /**
     * 员工列表查询
     * @param
     * @return
     */
    @Override
    public ResultBo getEmpAccNumList(ReqEmpAccNumBean req) {

       ResultBo result = ResultBo.build();
        //入参
        /**
         *         json.put("depParentId",depParentId);
                    json.put("departmentId", departmentId);
                    json.put("other", other);
                    json.put("page",super.page);
                    json.put("size",super.size);
         */
        Map<String,Object> map1 = req.getMap();
        MapUtil map = new MapUtil(map1);

      //todo
        Page<TEmployeeInfoEntity> page = this.pageTEmp(map);
       //todo
        PageResponseCommBean resp =this.pageToResp(page);
        System.out.println("=========resp.getTotalPages():"+resp.getTotalPages());
        System.out.println("=========resp.getTotalElements():"+resp.getTotalElements());
        System.out.println("=========resp.getContent():"+resp.getContent());
        //======================================================
        result.setResultBody(resp);
        return result;

    }

    /**
     * 从数据库中查询数据
     * @param map
     * @return
     */
    public Page<TEmployeeInfoEntity> pageTEmp(MapUtil map){
        Integer depParentId = map.getInteger("depParentId");
        Integer departmentId = map.getInteger("departmentId");
        String other = map.getString("other");
        //分页                                     当前页               每页显示条数    按照字段排序
        Pageable pageable = new PageRequest(map.getInteger("page") - 1, map.getInteger("size"), new Sort(Sort.Direction.DESC, "fId"));
        Page<TEmployeeInfoEntity> page = employeeInfoDao.findAll(
                new Specification<TEmployeeInfoEntity>() {

                    public Predicate toPredicate(Root<TEmployeeInfoEntity> root,
                                                 CriteriaQuery<?> query, CriteriaBuilder cb) {
                        List<Predicate> lstPredicates = new ArrayList<Predicate>();
                        //部门-1  全查
                        //部门非-1
                        //      看 父ID 0 根节点
                        //                子节点
                        if (departmentId != 0){
                            if(departmentId != -1){
                                if(depParentId == 0) {
                                    //                                    映射实体类字段                              请求入参字段
                                    lstPredicates.add(cb.equal(root.get("fDepartIdOne").as(Integer.class), departmentId));
                                }else{
                                    lstPredicates.add(cb.equal(root.get("fDepartIdTwo").as(Integer.class), departmentId));

                                }
                            }
                        }
                        if (StringUtils.isNotBlank(other)) {
                            lstPredicates.add(cb.like(root.get("fSearchKey").as(String.class), "%"+ other +"%"));
                        }
                        lstPredicates.add(cb.notEqual(root.get("fIsDelete").as(String.class),  "yes" ));
                        Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
                        return cb.and(lstPredicates.toArray(arrayPredicates));
                    }
                }, pageable);
        return page;
    }

    public PageResponseCommBean pageToResp(Page<TEmployeeInfoEntity> page){
        List<TEmployeeInfoEntity> list = page.getContent();
        PageResponseCommBean bean = new PageResponseCommBean();
        List<RespEmpAccNumBean> respList = new ArrayList<>();
        for (TEmployeeInfoEntity entity : list){

            RespEmpAccNumBean resp = new RespEmpAccNumBean();
            resp.setfId(entity.getfId());
            if(StringUtils.isNotBlank(String.valueOf(entity.getfAccount()))){
                resp.setfAccount(entity.getfAccount());
            }
            if(StringUtils.isNotBlank(String.valueOf(entity.getfName()))){
                resp.setfName(entity.getfName());
            }
            if(StringUtils.isNotBlank(String.valueOf(entity.getfPosition()))){
                resp.setfPosition(entity.getfPosition());
            }
            if(StringUtils.isNotBlank(String.valueOf(entity.getfDepartIdTwo()))){
                TDepartmentInfoEntity one = departmentInfoDao.findOne(entity.getfDepartIdTwo());
                if(one == null){
                    resp.setfDepartIdTwo("");
                }else{
                    resp.setfDepartIdTwo(one.getfName());
                }
            }
            if(StringUtils.isNotBlank(entity.getfMobile())){
                resp.setfMobile(entity.getfMobile());
            }

            if(StringUtils.isNotBlank(entity.getfEmail())){
                resp.setfEmail(entity.getfEmail());
            }

            if(StringUtils.isNotBlank(entity.getfStatus())){
                resp.setfStatus(entity.getfStatus());
            }
            respList.add(resp);
        }
        bean.setContent(respList);
        bean.setNumber(page.getNumber());
        bean.setSize(page.getSize());
        bean.setTotalElements(Integer.valueOf(String.valueOf(page.getTotalElements())));
        bean.setTotalPages(page.getTotalPages());
        return bean;
    }

//    public Boolean cheackMap(Map<String,Object> map) {
//        boolean bo = true;
//        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<String, Object> entry = it.next();
//            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
//            if(map.get(entry.getKey())==null){
//                return false;
//            }
//        }
//        return true;
//    }
}

第三步:MapUtil

package com.payease.scfordermis.utils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @Created By liuxiaoming
 * @CreateTime 2018/1/16 上午9:43
 **/
public class MapUtil {
    private Map<String,Object> map;

    public MapUtil(Map<String,Object> map){
        this.map = map;
    }

    /**
     * <p>
     * 根据Key返回一个Double型
     * </p>
     * @param key
     * @return Double
     */
    public Double getDouble(String key){
        if(map.get(key)!=null){
            if(map.get(key) instanceof Double){
                return (Double)map.get(key);
            }else{
                return 0.0;
            }
        }else{
            return 0.00;
        }
    }

    /**
     * <p>
     * 根据Key返回一个String
     * </p>
     * @param key
     * @return String
     */
    public String getString(String key){
        if(map.get(key)!=null){
            if(map.get(key) instanceof String){
                return (String)map.get(key);
            }else{
                return "";
            }
        }else{
            return "";
        }
    }

    /**
     * <p>
     * 根据Key返回一个Date
     * </p>
     * @param key
     * @return Date
     */
    public Date getDate(String key){
        if(map.get(key)!=null){
            if(map.get(key) instanceof Date){
                return (Date)map.get(key);
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * <p>
     * 根据Key返回一个Integer
     * </p>
     * @param key
     * @return Integer
     */
    public Integer getInteger(String key){
        if(map.get(key)!=null){
            if(map.get(key) instanceof Integer){
                return (Integer)map.get(key);
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }

    /**
     * <p>
     * 根据一个Key返回一个Map<String,String>
     * </p>
     * @param key
     * @return Map<String,String>
     */
    @SuppressWarnings("unchecked")
    public Map<String,String> getMap(String key){
        if(map.get(key)!=null){
            if(map.get(key) instanceof Map){
                return (Map<String,String>)map.get(key);
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * <p>
     * 根据key返回BigDecimal
     * 如果为null,则返回 new BigDecimal(0)
     * </p>
     * @param key
     * @return BigDecimal
     */
    public BigDecimal getBigDecimal(String key){
        if(map.containsKey(key)){
            if(map.get(key) instanceof BigDecimal){
                return (BigDecimal)map.get(key);
            }else{
                return new BigDecimal(0);
            }
        }else{
            return new BigDecimal(0);
        }
    }
}

第四步:RespEmpAccNumBean

package com.payease.scfordermis.bo.responseBo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * @Created By liuxiaoming
 * @CreateTime 2018/1/10 下午2:23
 **/
@ApiModel(value = "员工列表查询实体",description = "描述员工列表查询类")
public class RespEmpAccNumBean {
    @ApiModelProperty(value = "序号",dataType = "long",required = true)
    private long fId;
    @ApiModelProperty(value = "部门",dataType = "string",required = true)
    private String fDepartIdTwo;
    @ApiModelProperty(value = "账号",dataType = "string",required = true)
    private String fAccount;
    @ApiModelProperty(value = "账号状态:  open-开通 close-禁用 ",dataType = "string",required = true)
    private String fStatus;
    @ApiModelProperty(value = "姓名",dataType = "string",required = true)
    private String fName;
    @ApiModelProperty(value = "手机",dataType = "string",required = true)
    private String fMobile;
    @ApiModelProperty(value = "邮箱",dataType = "string",required = true)
    private String fEmail;
    @ApiModelProperty(value = "职位",dataType = "string",required = true)
    private String fPosition;

    public long getfId() {
        return fId;
    }

    public void setfId(long fId) {
        this.fId = fId;
    }

    public String getfDepartIdTwo() {
        return fDepartIdTwo;
    }

    public void setfDepartIdTwo(String fDepartIdTwo) {
        this.fDepartIdTwo = fDepartIdTwo;
    }

    public String getfAccount() {
        return fAccount;
    }

    public void setfAccount(String fAccount) {
        this.fAccount = fAccount;
    }


    public String getfStatus() {
        return fStatus;
    }

    public void setfStatus(String fStatus) {
        this.fStatus = fStatus;
    }

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getfMobile() {
        return fMobile;
    }

    public void setfMobile(String fMobile) {
        this.fMobile = fMobile;
    }

    public String getfEmail() {
        return fEmail;
    }

    public void setfEmail(String fEmail) {
        this.fEmail = fEmail;
    }

    public String getfPosition() {
        return fPosition;
    }

    public void setfPosition(String fPosition) {
        this.fPosition = fPosition;
    }

    @Override
    public String toString() {
        return "RespEmpAccNumBean{" +
                "fId=" + fId +
                ", fDepartIdTwo=‘" + fDepartIdTwo + ‘\‘‘ +
                ", fAccount=‘" + fAccount + ‘\‘‘ +
                ", fStatus=‘" + fStatus + ‘\‘‘ +
                ", fName=‘" + fName + ‘\‘‘ +
                ", fMobile=‘" + fMobile + ‘\‘‘ +
                ", fEmail=‘" + fEmail + ‘\‘‘ +
                ", fPosition=‘" + fPosition + ‘\‘‘ +
                ‘}‘;
    }
}

第五步:PageResponseCommBean

package com.payease.scfordermis.bo.responseBo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * @Author : zhangwen
 * @Data : 2018/1/10
 * @Description :
 */
@ApiModel(value = "分页公共返回类",description = "描述分页返回类")
public class PageResponseCommBean<T> extends PageBean{
    @ApiModelProperty(value = "结果集",dataType = "list")
    private T content;

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "PageResponseCommBean{" +
                "content=" + content +
                ‘}‘;
    }
}

第六步:PageBean

package com.payease.scfordermis.bo.responseBo;

import io.swagger.annotations.ApiModelProperty;

/**
 * @Created By liuxiaoming
 * @CreateTime 2018/1/10 下午2:02
 **/
public class PageBean {
    @ApiModelProperty(value = "当前页",dataType = "int",required = true)
    private Integer number;
    @ApiModelProperty(value =  "每页显示条数",dataType = "int",required = true)
    private Integer size;
    @ApiModelProperty(value =  "总条数",dataType = "int",required = true)
    private Integer totalElements;
    @ApiModelProperty(value =  "总页数",dataType = "int",required = true)
    private Integer totalPages;

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public Integer getSize() {
        return size;
    }

    public void setSize(Integer size) {
        this.size = size;
    }

    public Integer getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(Integer totalElements) {
        this.totalElements = totalElements;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

    @Override
    public String toString() {
        return "PageBean{" +
                "number=" + number +
                ", size=" + size +
                ", totalElements=" + totalElements +
                ", totalPages=" + totalPages +
                ‘}‘;
    }
}

第七步:测试

package com.payease.scfordermis;

import com.payease.scfordermis.bo.ResultBo;
import com.payease.scfordermis.bo.requestBo.ReqEmpAccNumBean;
import com.payease.scfordermis.service.EmpAccNumService;
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.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ScfOrderMisApplicationTests {
    @Autowired
    private EmpAccNumService empAccNumService;

    @Test
    public void contextLoads() {
        ReqEmpAccNumBean req = new ReqEmpAccNumBean();
        //req.setDepartmentId(-1);
        //req.setDepParentId();
        req.setDepartmentId(2);
        req.setDepParentId(1);
        req.setOther("1");
        ResultBo result = empAccNumService.getEmpAccNumList(req);
        System.out.println(result.toString());


//        Map<String,Object> map = req.getMap();
//        Boolean bo = new EmpAccNumServiceImpl().cheackMap(map);
//        System.out.println(bo);
    }

}

 

以上是关于spring jpa : 多条件查询的主要内容,如果未能解决你的问题,请参考以下文章

Spring Data JPA动态查询(多条件and)

Spring boot 之 使用JPA对数据进行复杂条件的查询

在Spring Boot中使用Spring-data-jpa实现分页查询(转)

如何利用spring data mongodb 进行多条件查询

Spring-Data-JPA 中的查询如何动态组装条件?

spring jpa 条件查询统计