spring date jpa 实现动态查询
来源:互联网 发布:新版淘宝怎么充话费 编辑:程序博客网 时间:2024/06/11 03:03
话不多说,直入正题,之前在百度上想找spring date jpa动态查询是怎么实现的,一直找不到,现在写一下我理解的,如有过错请大神指导。
首先在service层写一个内部类,继承 Specification<T> 接口,定义类型为实体类的属性,写有参构造给属性赋值,重写toPredicate方法。
代码如下:
//内部类实现Specification<T>接口
class ComResourceSpecification implements Specification<ComResource> {
//实体类的私有属性
private ComResource comResource;
public ComResourceSpecification(ComResource comResource) {
this.comResource = comResource;
}
// 查询条件拼接
public Predicate toPredicate(Root<ComResource> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
if (comResource == null) {
return null;
}
List<Predicate> list = new ArrayList<Predicate>();
// 关键字查询
if (StringUtils.isNotEmpty(comResource.getKeyWord())) {
list.add(cb.or(cb.like(root.get("comResName").as(String.class), "%" + comResource.getKeyWord() + "%"),
cb.like(root.get("address").as(String.class), "%" + comResource.getKeyWord() + "%"),
cb.like(root.get("contactPer").as(String.class), "%" + comResource.getKeyWord() + "%")
));
}
if (StringUtils.isNotEmpty(comResource.getOrgCode())) {
list.add(cb.equal(root.get("orgCode").as(String.class), comResource.getOrgCode()));
}
//更新时间
if(comResource.getStartTime() != null && comResource.getEndTime()!= null){
list.add(cb.between(root.get("updateTime").as(Date.class), comResource.getStartTime(), comResource.getEndTime()));
}else if(comResource.getStartTime() != null && comResource.getEndTime()== null){
list.add(cb.greaterThanOrEqualTo(root.get("updateTime").as(Date.class),comResource.getStartTime()));
}else if(comResource.getStartTime() == null && comResource.getEndTime() != null){
list.add(cb.lessThanOrEqualTo(root.get("updateTime").as(Date.class),comResource.getEndTime()));
}
Predicate[] p = new Predicate[list.size()];
query.where(cb.and(list.toArray(p)));
query.orderBy(cb.desc(root.get("updateTime").as(Date.class)));
return query.getRestriction();
}
}
需要注意的是,条件都放在list集合里,集合的条件都是以and拼接的,如需用 or 拼接将条件都添加在集合的一个元素中,祥见“关键字查询”那
- spring date jpa 实现动态查询
- Spring Data JPA 动态查询
- Spring Data JPA动态查询
- Spring data JPA使用Specification实现动态查询例子
- Spring Data JPA中的动态查询
- spring data jpa的动态查询封装
- Spring Data JPA中的动态查询
- spring jpa动态条件查询并分页
- spring data jpa动态条件查询
- JPA &Spring Date
- SpringData JPA 实现动态条件查询
- SpringBoot中使用Spring Data Jpa 实现简单的动态查询的两种方法
- Spring Data Jpa实现分页查询
- jpa date 多表查询
- Spring Data JPA动态查询 maven项目简单例子
- Spring data JPA中使用Specifications动态构建查询
- Spring Boot Jpa之构建动态SQL查询语句
- Spring data JPA中使用Specifications动态构建查询
- Java多线程(三)
- Flask之Flask类
- DOM补充
- Java学习中关于泛型2
- shiro ehcache
- spring date jpa 实现动态查询
- linux编程——I/O操作之文件阻塞|非阻塞
- Docker 基本操作命令
- 利用ARP欺骗+sslsplit实现ssl连接嗅探
- linux常用基础命令
- [LeetCode]628. Maximum Product of Three Numbers
- Codeforces Round #425 (Div. 2) D. Misha, Grisha and Underground
- 1929-打印矩形
- java ssl https 连接详解 生成证书