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. Hive入门指南

    转自:http://blog.csdn.net/zhoudaxia/article/details/8842576 1.安装与配置 Hive是建立在Hadoop上的数据仓库软件,用于查询和管理存放在分 ...

  2. 网上搜到的特别厉害的visio2019激活方法

    原文链接:https://blog.csdn.net/godot06/article/details/94141854 步骤如下: 1.电脑新建一个记事本文件.txt(任何地方都可以) 2.复制下面代 ...

  3. linux内核配置与编译

    配置内核:配置硬件和软件需的部分. make config:基于文本模式的交互式配置.(一问一答) make menuconfig:基于文本模式菜单性配置.(直观简单高效) <*>会产生b ...

  4. springboot中使用拦截器

    5.1 回顾SpringMVC使用拦截器步骤 自定义拦截器类,实现HandlerInterceptor接口 注册拦截器类 5.2 Spring Boot使用拦截器步骤 5.2.1        按照S ...

  5. C# 类的继承和访问

    学习笔记------类的继承和访问: class MyBaseClass { public void PrintSun(){ Console.WriteLine("base111111111 ...

  6. 记Springcloud Config Service整合gitlab一坑

    spring.cloud.config.server.git.uri=http://ip/***/configserver.git必须加上.git

  7. python 3 与python 2连接mongoDB的区别

    本文出自:https://www.cnblogs.com/2186009311CFF/p/11852010.html 好久前机缘巧合见识过量化投资,然而堵在了用python连接MongoDB数据库上, ...

  8. 使用oracle Sqlplus中上下键出现乱码的问题

    安装rlwrap,前提是安装readline和readline-devel yum list | grep readlineyum install -y readline.x86_64 readlin ...

  9. C# 2.0

    序言 泛型 为什么需要泛型? 分部类型 分部类和方法 partial 匿名方法 使用Delegate的时候很多时候没必要使用一个普通的方法,因为这个方法只有这个Delegate会用,并且只用一次,这时 ...

  10. 如何安装 Angular CLI 并且检查 CLI 的版本

    想在系统中安装 Angular CLI ,如何进行安装并且如何检查 CLI 的版本? 可以使用命令: npm install -g @angular/cli 进行安装. 使用命令 ng version ...