SpringDataJpa多条件查询代码封装
package com.pantech.cloud.mlogistics.util; import com.mysql.jdbc.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import java.util.Map; /**
* @author xzy
* @date 2019-11-25 10:15
* 说明:用于生成sort、pageable
*/
public class PageableUtils {
/**
* Meta = {"sortColumn":"","sortDirection":"","pageNumber","","pageSize":""}
* 排序字段、排序方向、页码、分页大小
*/
private Map<String, Object> meta = null;
private String sortColumn = null;
private String sortDirection = null;
private Integer pageNumber = null;
private Integer pageSize = null; public Map<String, Object> getMeta() {
return meta;
} public void setMeta(Map<String, Object> meta) {
this.meta = meta;
//排序字段和排序方向必须同时指定,且值不能为null
if (meta.containsKey("sortColumn") && meta.get("sortColumn") != null
&& meta.containsKey("sortDirection") && meta.get("sortDirection") != null) {
sortColumn = String.valueOf(meta.get("sortColumn"));
sortDirection = String.valueOf(meta.get("sortDirection"));
}
if (meta.containsKey("pageNumber") && !"".equals(meta.get("pageNumber"))
&& meta.containsKey("pageSize") && !"".equals(meta.get("pageSize"))) {
pageNumber = Integer.parseInt(meta.get("pageNumber").toString());
pageSize = Integer.parseInt(meta.get("pageSize").toString());
}
} public PageableUtils(Map<String, Object> meta) {
setMeta(meta);
} /**
* 获取排序条件
*/
public Sort getSort() {
Sort sort = null;
//确保排序字段有效,确保排序方向有效
if (StringUtils.isNullOrEmpty(sortColumn)) {
return null;
} else if ("ASC".equals(sortDirection) || "asc".equals(sortDirection)) {
sort = new Sort(Sort.Direction.ASC, sortColumn);
} else if ("DESC".equals(sortDirection) || "desc".equals(sortDirection)) {
sort = new Sort(Sort.Direction.DESC, sortColumn);
}
return sort;
} /**
* 获取分页条件
*
* @param sort - 排序条件
*/
public Pageable getPageable(Sort sort) {
Pageable pageable;
if (pageNumber == null || pageSize == null) {
pageable = null;
} else if (sort != null) {
pageable = PageRequest.of(pageNumber, pageSize, sort);
} else {
pageable = PageRequest.of(pageNumber, pageSize);
}
return pageable;
} public Pageable getPageable() {
Sort sort = getSort();
return getPageable(sort);
}
}
PageableUtils.java工具类负责从参数中提取排序、分页条件
package com.pantech.cloud.mlogistics.util; import com.pantech.cloud.common.msg.Message;
import com.pantech.cloud.common.msg.MessageBox;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.Repository; import java.util.Map; /**
* @author xzy
* @date 2019-11-25 10:26
* 说明:条件查询
*/
public class ConditionalQueryUtils<T extends JpaRepository & JpaSpecificationExecutor> { private T repository = null; public T getRepository() {
return repository;
} public void setRepository(T repository) {
this.repository = repository;
} public ConditionalQueryUtils(T repository) {
this.repository = repository;
} /**
* 条件查询:多条件查询||排序查询||分页查询
*
* @param specification - 多条件查询条件
* @param meta - 包含条件查询、分页查询条件
*/
public Message findByConditions(Specification specification, Map<String, Object> meta) {
PageableUtils pageableUtils = new PageableUtils(meta);
//排序条件
Sort sort = pageableUtils.getSort();
//分页条件
Pageable pageable = pageableUtils.getPageable();
/**
* 查询
*/
if (specification != null) {
//1、多条件查询
if (pageable != null) {
//1.1多条件查询+排序查询+分页查询
return new MessageBox<>(repository.findAll(specification, pageable));
} else {
if (sort != null) {
//1.2.1多条件查询+排序查询
return new MessageBox<>(repository.findAll(specification, sort));
} else {
//1.2.2多条件查询
return new MessageBox<>(repository.findAll(specification));
}
}
} else {
//2、查询所有数据
if (pageable != null) {
//2.1查询所有数据+排序查询+分页查询
return new MessageBox<>(repository.findAll(pageable));
} else {
if (sort != null) {
//2.2.1查询所有数据+排序查询
return new MessageBox<>(sort);
} else {
//2.2.2查询所有数据
return new MessageBox<>(repository.findAll());
}
}
}
}
}
使用说明:
1、Entity中包含参数
/**
* 附加参数
*/
@Transient
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
private Map<String, Object> meta = new HashMap<>();
2、Repository实现接口
package com.pantech.cloud.mlogistics.repository.ina; import com.pantech.cloud.mlogistics.entity.ina.WaybillReturnViewEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /**
* @author xzy
* @date 2019-11-25 09:43
* 说明:
*/
public interface WaybillReturnViewRepository extends JpaRepository<WaybillReturnViewEntity, String>, JpaSpecificationExecutor<WaybillReturnViewEntity> {
}
使用例子:
package com.pantech.cloud.mlogistics.service.impl.ina; import com.mysql.jdbc.StringUtils;
import com.pantech.cloud.common.msg.Message;
import com.pantech.cloud.mlogistics.entity.ina.WaybillReturnViewEntity;
import com.pantech.cloud.mlogistics.repository.ina.WaybillReturnViewRepository;
import com.pantech.cloud.mlogistics.service.ina.WaybillReturnViewService;
import com.pantech.cloud.mlogistics.util.ConditionalQueryUtils;
import com.pantech.cloud.mlogistics.util.SpecificationFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; /**
* @author xzy
* @date 2019-11-25 09:46
* 说明:
*/
@Service
public class WaybillReturnViewServiceImpl implements WaybillReturnViewService { private WaybillReturnViewRepository repository; @Autowired
public void dependenceInject(WaybillReturnViewRepository repository) {
this.repository = repository;
} /**
* 获取所有数据
*/
@Override
public List<WaybillReturnViewEntity> findAll() {
return repository.findAll();
} /**
* 多条件查询
*
* @param conditions - 查询条件
* @return - 返回符合条件的数据
*/
@Override
public Message findByConditions(WaybillReturnViewEntity conditions) {
Specification specification = getConditions(conditions);
ConditionalQueryUtils<WaybillReturnViewRepository> conditionUtils = new ConditionalQueryUtils<>(repository);
return conditionUtils.findByConditions(specification, conditions.getMeta());
} /**
* 确认查询条件
*
* @param conditions - 包含查询条件的实体
* @return - 查询条件
*/
private Specification getConditions(WaybillReturnViewEntity conditions) {
List<Specification> specificationList = new ArrayList<>();
Specification specification = null; //主单号
if (!StringUtils.isNullOrEmpty(conditions.getMainBill())) {
specificationList.add(SpecificationFactory.equal("mainBill", conditions.getMainBill()));
}
//分单号
if (!StringUtils.isNullOrEmpty(conditions.getHawbBill())) {
specificationList.add(SpecificationFactory.equal("hawbBill", conditions.getHawbBill()));
}
//退货客户
if (!StringUtils.isNullOrEmpty(conditions.getCustomerName())) {
specificationList.add(SpecificationFactory.equal("customerName", conditions.getCustomerName()));
}
if (conditions.getMeta().containsKey("returnDateLeft") && !"".equals(conditions.getMeta().get("returnDateLeft").toString())) {
Date returnDateLeft = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
returnDateLeft = dateFormat.parse(conditions.getMeta().get("returnDateLeft").toString());
} catch (ParseException e) {
e.printStackTrace();
}
specificationList.add(SpecificationFactory.greaterOrEqual("returnDate", (Date) returnDateLeft));
}
if (conditions.getMeta().containsKey("returnDateRight") && !"".equals(conditions.getMeta().get("returnDateRight").toString())) {
Date returnDateRight = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
returnDateRight = dateFormat.parse(conditions.getMeta().get("returnDateRight").toString());
} catch (ParseException e) {
e.printStackTrace();
}
specificationList.add(SpecificationFactory.smallerOrEqual("returnDate", returnDateRight));
} for (Specification spec : specificationList) {
if (specification == null) {
specification = spec;
} else {
specification = specification.and(spec);
}
}
return specification;
}
}
请求参数:

SpringDataJpa多条件查询代码封装的更多相关文章
- spring-data-jpa动态条件查询
//获取动态条件的集合List<Long> list = new ArrayList<Long>(); Long sysUserId = currentUser.getSysU ...
- 03_MyBatis基本查询,mapper文件的定义,测试代码的编写,resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询ma
1 PersonTestMapper.xml中的内容如下: <?xmlversion="1.0"encoding="UTF-8"?> < ...
- 分页查询关键代码 多条件查询关键代码 删除选中商品关键代码 修改要先回显再修改 修改要先回显再修改 同一业务集中使用同一servlet的方法
分页查询关键代码: 通过servlet转发回来的各种信息进行分页的设计(转发回的信息有 分页查询的List集合 查询的页码 查询的条数 查询的数据库总条数 查询的总页码) 从开始时循环10次出现十个数 ...
- elasticsearch组合多条件查询实现restful api以及java代码实现
原文:http://blog.java1234.com/blog/articles/372.html elasticsearch组合多条件查询实现restful api以及java代码实现 实际开发中 ...
- spring-data-jpa 介绍 复杂查询,包括多表关联,分页,排序等
本篇进行Spring-data-jpa的介绍,几乎涵盖该框架的所有方面,在日常的开发当中,基本上能满足所有需求.这里不讲解JPA和Spring-data-jpa单独使用,所有的内容都是在和Spring ...
- SpringData JPA快速入门和基本的CRUD操作以及Specifications条件查询
SpringData JPA概述: SpringData JPA 是 Spring 基于 ORM 框架.JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作 ...
- [NHibernate]条件查询Criteria Query
目录 写在前面 文档与系列文章 条件查询 一个例子 总结 写在前面 上篇文章介绍了HQL查询,我个人觉得使用ORM框架就是为了让少些sql,提高开发效率,而再使用HQL就好像还是使用sql,就觉得有点 ...
- orm 通用方法——GetOneModel 条件查询一个对象
数据连接层的方法封装成通用方法是很有必要,节省不必要的重复写代码. Golang的orm.xorm框架没有封装这些操作. 这里是一个查询单个对象的方法. 此处抛砖引玉,大家继续完善. 通用方法定义代码 ...
- ThinkPHP中 按条件查询后列表显示
最近在项目中遇到了需要根据下拉框的条件筛选出符合条件的数据,然后进行列表显示的问题. 在ThinkPHP中进行列表显示的传统过程:通过在后台控制器中查询出数据,然后通过$this->assign ...
随机推荐
- Data Flow-File Read-详细过程
- saltStack_Pillar
Pillar是Salt非常重要的一个组件,它用于给特定的minion定义任何你需要的数据,这些数据可以被Salt的其他组件使用.这里可以看出Pillar的一个特点,Pillar数据是与特定minion ...
- Angular项目目录结构
前言:不支持MakeDown的博客园调格式的话,真的写到快o(╥﹏╥)o了,所以老夫还是转战到CSDN吧,这边就不更新啦啦啦~ CSDN地址:https://blog.csdn.net/Night20 ...
- js利用select标签生成简易计算功能
html中使用select option作为运算符的承接容器,输入值,选择不同运算符,计算结果. 文章地址 https://www.cnblogs.com/sandraryan/ <!DOCTY ...
- webpack学习(五)entry和output的基础配置
1:entry和output就是打包的入口和出口的两个对象.但是如果入口文件就一个的话(应该说只希望打包出一个脚本文件), entry直接跟一个字符串(入口文件路径)就可以了.如:entry : &q ...
- Python--day42--mysql操作数据库及数据表和基本增删改查
sql语法规则: 一.操作文件夹 1.创建数据库db2:create database db2; 2.创建数据库db2并标明数据库的编码格式为utf8:create database db2 defa ...
- 51nod 1380"夹克老爷的逢三抽一"(贪心+set)
传送门 •参考资料 [1]:51Nod-1380-夹克老爷的逢三抽一 •题意 从长度为 n 的数组中抽取 $\frac{n}{3}$ 个不相邻的值使得加和最大(首尾也不能同时取) •题解 贪心选择当前 ...
- H3C 动态路由协议的基本原理
- linux初始化和关停
如已提到的, 模块初始化函数注册模块提供的任何功能. 这些功能, 我们指的是新功能, 可以由应用程序存取的或者一整个驱动或者一个新软件抽象. 实际的初始化函数定义常常 如: static int ...
- 使用Python内置的smtplib包和email包来实现邮件的构造和发送。
此文章github地址:https://github.com/GhostCNZ/Python_sendEmail Python_sendEmail 使用Python内置的smtplib包和email包 ...