spring jpa : 多条件查询
https://www.cnblogs.com/Donnnnnn/p/6277872.html
方式一:
第一步: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 : 多条件查询的更多相关文章
- jpa多条件查询重写Specification的toPredicate方法(转)
Spring Data JPA支持JPA2.0的Criteria查询,相应的接口是JpaSpecificationExecutor.Criteria 查询:是一种类型安全和更面向对象的查询 . 这个接 ...
- jpa多条件查询
首先继承JpaSpecificationExecutor<T>接口 需要用到JpaSpecificationExecutor<T>中的Page<T> findAll ...
- Spring Boot Jpa 多条件查询+排序+分页
事情有点多,于是快一个月没写东西了,今天补上上次说的. JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将 ...
- spring data jpa 组合条件查询封装
/** * 定义一个查询条件容器 * @author lee * * @param <T> */ public class Criteria<T> implements Spe ...
- springboot jpa 多条件查询(多表)
前几天写的,贴上来. 实体类. package com.syl.demo.daomain; import lombok.Data; import javax.persistence.*; /** * ...
- springboot jpa 多条件查询(单表)
需要实现的功能: 多个搜索输入框:全部不填,则查出所有列表:填了条件,就按条件查找:填的条件个数不定. 方法实现的核心:jpa自带的Specification<T> (目前只需要单表,多表 ...
- spring jpa 自定义查询数据库的某个字段
spring jpa 提供的查询很强大, 就看你会不会用了. 先上代码, 后面在解释吧 1. 想查单个表的某个字段 在repository中 @Query(value = "select i ...
- 使用Spring JPA中Page、Pageable接口和Sort类完成分页排序
显示时,有三个参数,前两个必填,第几页,一页多少个size,第三个参数默认可以不填. 但是发现这个方法已经过时了,通过查看它的源码发现,新方法为静态方法PageRequest of(page,size ...
- Spring MVC和Spring Data JPA之按条件查询和分页(kkpaper分页组件)
推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有, 后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 ...
随机推荐
- VSFTPD+MYSQL+PAM
一 需要的软件包: 1. vsftpd: 2.MySQL 3.pam_mysql 4.pam-devel 5.openssl 6.tcp-wrappers 二 ...
- 后台开发 - DPDK引发的图谱
关系图谱(点击看完整大图): 部分名词: 名词 全写 解释 备注 DPDK Data Plane Development Kit 数据平面开发套件或叫数据平面开发工具集 Intel开源的快速数据包处理 ...
- C++标准库addressof的应用
C++11将addressof作为标准库的一部分,用于取变量和函数等内存地址. 代码示例: #include <memory> #include <stdio.h> void ...
- XCode中常用错误解决
No such file or directory 解决方法(可以依次尝试,总有一种能最终解决问题): 方法1.退出Xcode,然后从finder里面进入~/Library/ ...
- 20169207《Linux内核原理与分析》第六周作业
这周的作业同样分为两部分,第一部分的学习MOOC第四节[扒开系统调用的三层皮],并结合实验楼的实验四深入学习.第二部分阅读学习教材「Linux内核设计与实现 (Linux Kernel Develop ...
- Android Caused by: java.lang.IllegalArgumentException: column '_id' does not exist
出错原因:在查询整个sqlite数据库时,没有查询到 "_id" 这一列. 原来的代码是:mSQLiteDatabase.query(table_name, new String[ ...
- 转一篇用分布式解决ERP问题
https://www.cnblogs.com/liuche/p/7955462.html
- hdu 3015
这个题给你一堆树,每棵树的位置x和高度h都给你 f[i]代表这棵树的位置排名,s[i]代表这棵树的高度排名 问你任意两棵树的(f[i] - f[j])*min(s[i],s[j])和 (f[i]-f[ ...
- ES基本操作
倒排索引 ElasticSearch使用一种称为倒排索引的结构,它适用于快速的全文搜索.一个倒排索引由文档中所有不重复词的列表构成,对于其中每个词,有一个包含它的文档列表. 查询 # 查看索引配置GE ...
- bootstrap4相关文档
本节课我们主要学习一下Bootstrap的两个个组件功能:输入框组件和导航导航条组件. 一.输入框组件 文本输入框就是可以在<input>元素前后加上文字或按钮,可以实现对表单控件的扩 展 ...