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. [C#] 如何分析stackoverflow等clr错误

    有时候由于无限递归调用等代码错误,w3wp.exe会报错退出,原因是clr.exe出错了. 这种错误比较难分析,因为C#代码抓不住StackOverflowException等异常. 处理方法是:生成 ...

  2. ocilib linux编译安装

    1.首先下载ocilib到自己目录 github:https://github.com/vrogier/ocilib 2.在下载instantclient 11.2.2的文件: instantclie ...

  3. Open Source GIS and Freeware GIS Applications

    Open Source GIS and Freeware GIS Applications   An open source application by definition is software ...

  4. uni-app设置 video开始播放进入全屏状态

    有一video标签 <video id="myVideo" :src="videoUrl"></video> 获取 video 上下文 ...

  5. @noi.ac - 490@ game

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 小 Q 和小 T 正在玩一种双人游戏.m 张木牌从左往右排成一排 ...

  6. Top 10 open source projects of 2015

    Top 10 open source projects of 2015 Posted 15 Dec 2015Jen Wike Huger (Red Hat)Feed 188 up 31 comment ...

  7. Jquery FormData文件异步上传 快速指南

    网站中文件的异步上传是个比较麻烦的问题,不过现在通过jquery 可以很容易的解决这个问题: 使用jquery2.1版本,较老版本不支持异步文件上传功能: 表单代码: <form id=&quo ...

  8. hdu 1595 find the longest of the shortest(迪杰斯特拉,减去一条边,求最大最短路)

    find the longest of the shortest Time Limit: 1000/5000 MS (Java/Others)    Memory Limit: 32768/32768 ...

  9. TCP/IP模型的层次结构

  10. HDU 1864 01背包、

    这题题意有点坑阿.感觉特别模糊. 我开始有一点没理解清楚.就是报销的话是整张整张支票报销的.也是我傻逼了 没一点常识 还有一点就是说单张支票总额不超过1000,每张支票中单类总额不超过600,我开始以 ...