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 ...
随机推荐
- 【SDOI2015】bzoj3990 排序
A. 排序 题目描述 输入格式 输出格式 一行,一个整数,表示可以将数组A从小到大排序的不同的操作序列的个数. 样例 样例输入 3 7 8 5 6 1 2 4 3 样例输出 6 数据范围与提示 对于3 ...
- vue filter使用方法
Vue.js 允许你自定义过滤器,可被用于一些常见的文本格式化. 过滤器可以用在两个地方:双花括号插值和 v-bind 表达式 (后者从 2.1.0+ 开始支持). 过滤器应该被添加在 JavaScr ...
- video 获取第一帧的图片作为封面
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...
- supersocket新的配置属性 "textEncoding"
在 SuperSocket 1.6 之前的版本, 当你通过Session对象发送文本时, 将文本信息转换成能够通过Socket传输的二进制数据的默认编码是UTF8. 你可以通过设置 Session 的 ...
- laravel validate 设置为中文(验证提示为中文)
把 resources\lang 下en 的文件夹 复制在同一目录并改名为 zn 把zn 中的 validation.php文件修改为 https://laravel-china.org/articl ...
- 【原生JS】进阶最后一个编程篇(与之前的选项卡不同的做法)
完成效果图: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UT ...
- Python--day42--MySQL外键定义及创建
什么是外键? 外键的创建:constraint 外键名 foregin key ("表1值1",“ 表1值2”) references 表2的名字(“值1”)
- Python--day60--一个简单(不完整)的web框架
- 2019-8-4-自动更新所有-Git-仓库
title author date CreateTime categories 自动更新所有 Git 仓库 lindexi 2019-08-04 14:44:59 +0800 2019-08-01 2 ...
- H3C 动态路由协议在协议栈中的位置