import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
import com.xxx.controller.logManage.LogSearchParamDTO;
import com.xxx.controller.trade.TradeParams;
/**
 * 改进方向 1:能不能 通过反射 ,只要---
 * 相关知识请自行查阅JPA Criteria查询
// 过滤条件
// 1:过滤条件会被应用到SQL语句的FROM子句中。在criteria
// 查询中,查询条件通过Predicate或Expression实例应用到CriteriaQuery对象上。
// 2:这些条件使用 CriteriaQuery .where 方法应用到CriteriaQuery 对象上
// 3:CriteriaBuilder也作为Predicate实例的工厂,通过调用CriteriaBuilder 的条件方法(
// equal,notEqual, gt, ge,lt, le,between,like等)创建Predicate对象。
// 4:复合的Predicate 语句可以使用CriteriaBuilder的and, or andnot 方法构建。
 * @author 小言
 * @date 2017年11月27日
 * @time 上午10:44:53
 * @version ╮(╯▽╰)╭
 */
public class SpecificationBuilderForOperateLog {

public static <T> Specification buildSpecification(Class<T> clazz,
            final LogSearchParamDTO logSearchParamDTO) {
        return new Specification<T>() {
            @Override
            public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicate = new ArrayList<Predicate>();
                Timestamp startTime = logSearchParamDTO.getStartTime();
                Timestamp endTime = logSearchParamDTO.getEndTime();
                // 时间段
                if (startTime != null && endTime != null) {
                    predicate.add(cb.between(root.<Timestamp> get("logTime"), startTime, endTime));
                }
                // 操作日志查询栏
                String searchCondition = logSearchParamDTO.getSearchCondition();
                if (searchCondition != null && !searchCondition.equals("")) {
                    predicate.add(cb.or(cb.equal(root.<String> get("operatorName"), searchCondition),
                            cb.equal(root.<String> get("operatorId"), searchCondition)));
                }
                // 操作日志用户类型
                String operatorType = logSearchParamDTO.getOperatorType();
                System.out.println("operatorType=="+operatorType);
                if (operatorType != null ){
                    predicate.add(cb.equal(root.<String> get("operatorType"), operatorType));
                }
                Predicate[] pre = new Predicate[predicate.size()];
//              System.out.println("pre=="+predicate.toArray(pre));
                query.where(predicate.toArray(pre));
                return query.getRestriction();
            }
        };
    }
}

下面是实际开发例子:

controller层

 @Controller
@RequestMapping(value = "/operateLog")
public class BgOperateLogController { @Autowired
private BgOperateLogService bgOperateLogService; @ResponseBody
@PostMapping("/findOperateLogByCondition")
public Result findOperateLogByCondition(@RequestBody LogSearchParamDTO logSearchParamDTO) {
System.out.println("logSearchParamDTO="+logSearchParamDTO);
Map<String, Object> result = new HashMap<>();
String start = logSearchParamDTO.getStart();
String end = logSearchParamDTO.getEnd();
if (start != null && end == null) {
return new Result(1001, "操作日志查询错误,时间参数缺少结束时间", result);
}
if (end != null && start == null) {
return new Result(1001, "操作日志查询错误,时间参数缺少开始时间", result);
}
//时间
long startTimeTimestamp = 0L;
long endTimeTimestamp = System.currentTimeMillis();
if(start != null && end != null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startTime;
Date endTime;
try {
startTime = sdf.parse(start);
endTime = sdf.parse(end);
startTimeTimestamp = startTime.getTime();
endTimeTimestamp = endTime.getTime();
} catch (ParseException e) {
e.printStackTrace();
return new Result(1001, "操作日志查询错误,转换日期出错", result);
}
}
String condition = logSearchParamDTO.getSearchCondition();
Integer pageNumber = logSearchParamDTO.getPageNumber()-1;
Integer pageSize = logSearchParamDTO.getPageSize() ;
String operatorType =logSearchParamDTO.getOperatorType();
Page<BgOperateLog> findByCondition = bgOperateLogService.findByCondition(new Timestamp(startTimeTimestamp),
new Timestamp(endTimeTimestamp),
condition,operatorType, pageNumber, pageSize);
// 这些字段必须有,暂时没有做校验
List<BgOperateLog> list = findByCondition.getContent();
result.put("totalPages", findByCondition.getTotalPages());
result.put("pageNumber", pageNumber+1);
result.put("list", list);
return new Result(1002, "操作日志查询成功", result);
} }

BgOperateLogController

DTO

 @Data
public class LogSearchParamDTO {
//前端传来的时间参数
private String start;
private String end;
private Timestamp startTime;
private Timestamp endTime;
private String searchCondition;
//操作日志查询参数
//操作用户类型(0,消费者,1商家,2后台人员)
private String operatorType;
private Integer pageNumber;
private Integer pageSize;
//登陆日志查询条件
public LogSearchParamDTO(Timestamp startTime, Timestamp endTime, String searchCondition) {
this.startTime = startTime;
this.endTime = endTime;
this.searchCondition = searchCondition;
}
public LogSearchParamDTO() {}
//操作日志查询条件
public LogSearchParamDTO(Timestamp startTime, Timestamp endTime, String searchCondition, String operatorType) {
this.startTime = startTime;
this.endTime = endTime;
this.searchCondition = searchCondition;
this.operatorType = operatorType;
}
}

LogSearchParamDTO

service 层

 @Override
public Page<BgOperateLog> findByCondition(Timestamp start,
Timestamp end, String condition ,String operatorType,
int pageNumber, int pageSize) {
Sort sort = new Sort(Sort.Direction.DESC, "logTime");
Pageable pageable = new PageRequest(pageNumber, pageSize, sort);
LogSearchParamDTO operateLog = new LogSearchParamDTO(start, end, condition,operatorType);
Page<BgOperateLog> page = bgOperateLogDao
.findAll(SpecificationBuilderForOperateLog.buildSpecification(BgOperateLog.class,operateLog), pageable);
return page;
}

dao层

 import java.io.Serializable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import com.xxx.entity.BgOperateLog;
@Repository
public interface BgOperateLogDao extends JpaRepository<BgOperateLog, Serializable>,JpaSpecificationExecutor<BgOperateLog>{}

entity层

 @Data
@Entity
public class BgOperateLog implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String logText;
private String operatorId;
private String operatorName;
private String operatorType;
private String ip;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Timestamp logTime;
}

转自:

https://blog.csdn.net/dgutliangxuan/article/details/78644464

https://blog.csdn.net/u011726984/article/details/72627706

参考:

https://www.cnblogs.com/vcmq/p/9484398.html

https://www.cnblogs.com/g-smile/p/9177841.html

Spring Data JPA 动态拼接条件的通用设计模式的更多相关文章

  1. springboot整合spring data jpa 动态查询

    Spring Data JPA虽然大大的简化了持久层的开发,但是在实际开发中,很多地方都需要高级动态查询,在实现动态查询时我们需要用到Criteria API,主要是以下三个: 1.Criteria ...

  2. Spring Data JPA 复杂/多条件组合查询

    1: 编写DAO类或接口  dao类/接口 需继承 public interface JpaSpecificationExecutor<T> 接口: 如果需要分页,还可继承 public ...

  3. Spring MVC和Spring Data JPA之按条件查询和分页(kkpaper分页组件)

    推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有, 后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 ...

  4. spring data jpa实现多条件查询(分页和不分页)

    目前的spring data jpa已经帮我们干了CRUD的大部分活了,但如果有些活它干不了(CrudRepository接口中没定义),那么只能由我们自己干了.这里要说的就是在它的框架里,如何实现自 ...

  5. spring data jpa 动态查询(工具类封装)

    利用JPA的Specification<T>接口和元模型就实现动态查询了.但是这样每一个需要动态查询的地方都需要写一个这样类似的findByConditions方法,小型项目还好,大型项目 ...

  6. 序列化表单为json对象,datagrid带额外参提交一次查询 后台用Spring data JPA 实现带条件的分页查询 多表关联查询

    查询窗口中可以设置很多查询条件 表单中输入的内容转为datagrid的load方法所需的查询条件向原请求地址再次提出新的查询,将结果显示在datagrid中 转换方法看代码注释 <td cols ...

  7. Spring Data JPA动态查询(多条件and)

    entity: @Entity @Table(name = "data_illustration") public class Test { @Id @GenericGenerat ...

  8. Spring Data JPA 复杂/多条件组合分页查询

    推荐视频: http://www.icoolxue.com/album/show/358 public Map<String, Object> getWeeklyBySearch(fina ...

  9. 【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现

    一.不带有动态条件的查询 分页的实现 实例代码: controller:返回的是Page<>对象 @Controller @RequestMapping(value = "/eg ...

随机推荐

  1. 从程序员小仙飞升上神,java技术开发要如何实现?

    新霸哥是一个专业从事java开发的,近期,新霸哥发现很多的朋友在问,从程序员小仙飞升上神难吗?在此新霸哥将为你详细的介绍,下面新霸哥将从新手入门和老司机进阶多方面详细的为大家介绍一下. 说起java首 ...

  2. centos7搭建ntp时间同步服务器chrony服务

    centos7搭建ntp时间同步服务器chrony服务 前言: 在centos6的时候我们基本使用的是ntp服务用来做时间同步,但是在centos7后推荐是chrony作为时间同步器的服务端使用, ...

  3. [傻瓜式一步到位] 阿里云服务器Centos上部署一个Flask项目

    网络上关于flask部署Centos的教程有挺多,不过也很杂乱. 在我第一次将flask上传到centos服务器中遇到了不少问题,也费了挺大的劲. 在参考了一些教程,并综合了几个教程之后才将flask ...

  4. Python之基于十六进制判断文件类型

    核心代码: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : suk import struct from io import Byt ...

  5. 阿里云服务器(Linux)上打开新端口

    1.配置安全组: 2.开放防火墙规则 查看想开的端口是否已开 # firewall-cmd --query-port=8888/tcp    提示no表示未开 开永久端口号 firewall-cmd ...

  6. 《python cookbook》学习笔记

    2016.5.3 第8章  类与对象 8.1 改变对象的字符串显示 __str__ 和 __repr__   %s 和 %r,提到了eval,我没有用过 8.2 自定义字符串的格式化  __forma ...

  7. Codeforces Round #560 Div. 3

    题目链接:戳我 于是...风浔凌弱菜又去写了一场div.3 总的来说,真的是比较简单.......就是.......不开long long见祖宗 贴上题解-- A 给定一个数,为01串,每次可以翻转一 ...

  8. 微信支付(公众号)爬坑记,包含 total_fee 失败和 JSAPI 签名验证失败等等

    做商城类网站不免会需要做支付功能,目前在中国大陆通用的做法就是使用支付宝支付和微信支付,上一篇博文已经讲个支付宝支付. 这篇文章来讲一讲微信支付,微信支付的方式有很多种,本文主要讲 JSAPI 支付的 ...

  9. Python3学习笔记(十六):随机数模块random

    一.random模块 1.random.random(): 返回0-1之间的随机浮点数 import random print(random.random()) 0.9348690085059901 ...

  10. 如何在matalb图像上添加公式符号

    方法: legend({'$\sigma(t)$'},'interpreter','latex') 效果如下: