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 基础 --初识Python

    python的起源 python是一门 解释型弱类型编程语言. 特点: 简单.明确.优雅 python的解释器 CPython. 官方提供的. 内部使用c语言来实现 PyPy. 一次性把我们的代码解释 ...

  2. ImportError: No module named libqt_gui_cpp_shiboken

    在使用 rosrun rqt_publisher rqt_publisher 调用ROS图形化界面的过程中出现: 而且在使用图像化界面添加/cmd_vel时,无法添加,命令窗口显示“段错误”. 在网上 ...

  3. vue2——指令渲染,{{}}渲染

    博客地址 :https://www.cnblogs.com/sandraryan/ 声明式的渲染,以{{}}的形式调用数据 <!DOCTYPE html> <html lang=&q ...

  4. poj 3528 Ultimate Weapon (3D Convex Hull)

    3528 -- Ultimate Weapon 一道三维凸包的题目,题目要求求出三维凸包的表面积.看懂了网上的三维凸包的代码以后,自己写的代码,跟网上的模板有所不同.调了一个晚上,结果发现错的只是数组 ...

  5. 【原生JS】动态分页样式效果

    效果图如下: html: <body> <div> <table id="btnbox"> <tbody> <tr>&l ...

  6. springmvc url处理映射的三种方式:

    一.SpringMVC简介 SpringMVC是一种基于Spring实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,使用了MVC架构模式的思想,将web层进行职责解耦,并管理应用所需对象 ...

  7. jQuery中动态创建、添加元素的方法总结

    <input type="button" value="创建元素" id="btn"> <div id="box ...

  8. H3C 配置Basic NAT

  9. fatal: Not a git repository (or any of the parent directories)

    当从github.com上面下载下了Firmware后,无意中删除了Firmware目录下的.git文件夹,再去编译就会出现:   fatal: Not a git repository (or an ...

  10. H3C 环路避免机制五:抑制时间