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多条件查询代码封装的更多相关文章

  1. spring-data-jpa动态条件查询

    //获取动态条件的集合List<Long> list = new ArrayList<Long>(); Long sysUserId = currentUser.getSysU ...

  2. 03_MyBatis基本查询,mapper文件的定义,测试代码的编写,resultMap配置返回值,sql片段配置,select标签标签中的内容介绍,配置使用二级缓存,使用别名的数据类型,条件查询ma

     1 PersonTestMapper.xml中的内容如下: <?xmlversion="1.0"encoding="UTF-8"?> < ...

  3. 分页查询关键代码 多条件查询关键代码 删除选中商品关键代码 修改要先回显再修改 修改要先回显再修改 同一业务集中使用同一servlet的方法

    分页查询关键代码: 通过servlet转发回来的各种信息进行分页的设计(转发回的信息有 分页查询的List集合 查询的页码 查询的条数 查询的数据库总条数 查询的总页码) 从开始时循环10次出现十个数 ...

  4. elasticsearch组合多条件查询实现restful api以及java代码实现

    原文:http://blog.java1234.com/blog/articles/372.html elasticsearch组合多条件查询实现restful api以及java代码实现 实际开发中 ...

  5. spring-data-jpa 介绍 复杂查询,包括多表关联,分页,排序等

    本篇进行Spring-data-jpa的介绍,几乎涵盖该框架的所有方面,在日常的开发当中,基本上能满足所有需求.这里不讲解JPA和Spring-data-jpa单独使用,所有的内容都是在和Spring ...

  6. SpringData JPA快速入门和基本的CRUD操作以及Specifications条件查询

    SpringData JPA概述: SpringData JPA 是 Spring 基于 ORM 框架.JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作 ...

  7. [NHibernate]条件查询Criteria Query

    目录 写在前面 文档与系列文章 条件查询 一个例子 总结 写在前面 上篇文章介绍了HQL查询,我个人觉得使用ORM框架就是为了让少些sql,提高开发效率,而再使用HQL就好像还是使用sql,就觉得有点 ...

  8. orm 通用方法——GetOneModel 条件查询一个对象

    数据连接层的方法封装成通用方法是很有必要,节省不必要的重复写代码. Golang的orm.xorm框架没有封装这些操作. 这里是一个查询单个对象的方法. 此处抛砖引玉,大家继续完善. 通用方法定义代码 ...

  9. ThinkPHP中 按条件查询后列表显示

    最近在项目中遇到了需要根据下拉框的条件筛选出符合条件的数据,然后进行列表显示的问题. 在ThinkPHP中进行列表显示的传统过程:通过在后台控制器中查询出数据,然后通过$this->assign ...

随机推荐

  1. Python从文件中读取内容,包含中文和英文

    读取文件内容使要和保存文件时的格式一致 以UTF-8格式保存文件,如: 读取: 在.py起始行写入:#-*- coding:utf-8 -*- filename = raw_input(u" ...

  2. mysql 连接慢的问题

    现象: 今发现站点訪问数据库变慢,经查,查询数据库非常快,连接数据库比較耗时. 解决的方法: 在mysql的配置文件my.cnf中,在[mysqld]以下加上这个配置就能够了. 附录:[mysqld] ...

  3. oracle函数 SUBSTRB(c1,n1[,n2])

    [功能]取子字符串 [说明]多字节符(汉字.全角符等),按2个字符计算 [参数]在字符表达式c1里,从n1开始取n2个字符;若不指定n2,则从第y个字符直到结束的字串. [返回]字符型,如果从多字符右 ...

  4. @bzoj - 4709@ 柠檬

    目录 @desription@ @solution@ @accepted code@ @details@ @desription@ 一共有 N 只贝壳,编号为 1...N,贝壳 i 的大小为 si. ...

  5. mysql数据库之mysql下载与设置

    下载和安装mysql数据库 mysql为我们提供了开源的安装在各个操作系统上的安装包,包括ios,liunx,windows. mysql的安装,启动和基础配置-------linux版本 mysql ...

  6. hdu 4063 Aircraft (Geometry + SP)

    Problem - 4063 几何加简单最短路. 题意是给出若干圆的圆心以及半径,求出从给出的起点到终点的最短路径的长度,可以移动的区域是圆覆盖到的任意一个位置. 做法是这样的,对圆两两求交点,用这些 ...

  7. php中 array_filter函数 的总结

    1.用此函数来过滤数组中的空元素 $arr1 = array('a'=>1,'b'=>0,'c'=>'','d'=>null,'e'=>5,'f'=>false); ...

  8. vue+file-saver+xlsx导出table表格为excel

    https://blog.csdn.net/wjswangjinsheng/article/details/91393396

  9. H3C PPP MP配置示例三

  10. Linux 查看iptables状态-重启

    iptables 所在目录 : /etc/sysconfig/iptables # service iptables status #查看iptables状态 # service iptables r ...