//dao层  继承 扩展仓库接口JpaSpecificationExecutor   (JPA 2引入了一个标准的API)
public interface CreditsEventDao extends JpaRepository<CreditsEventBean, Integer>, JpaSpecificationExecutor<CreditsEventBean>{}

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/      官方文档 -- 5.5. Specifications!

JpaSpecificationExecutor提供了以下接口:

/**
* Interface to allow execution of {@link Specification}s based on the JPA criteria API.
*
* @author Oliver Gierke
*/
public interface JpaSpecificationExecutor<T> { /**
* Returns a single entity matching the given {@link Specification}.
* 返回与给定的{@link规范}匹配的单个实体
* @param spec
* @return
*/
T findOne(Specification<T> spec); /**
* Returns all entities matching the given {@link Specification}.
* 返回与给定的{@link规范}匹配的所有实体。
* @param spec
* @return
*/
List<T> findAll(Specification<T> spec); /**
* Returns a {@link Page} of entities matching the given {@link Specification}.
* 返回与给定的{@link规范}匹配的实体的{@link页面}。
* @param spec
* @param pageable
* @return
*/
Page<T> findAll(Specification<T> spec, Pageable pageable); /**
* Returns all entities matching the given {@link Specification} and {@link Sort}.
* 返回与给定的{@link规范}和{@link排序}匹配的所有实体。
* @param spec
* @param sort
* @return
*/
List<T> findAll(Specification<T> spec, Sort sort); /**
* Returns the number of instances that the given {@link Specification} will return.
* 返回给定的{@link规范}将返回的实例数量。
* @param spec the {@link Specification} to count instances for
* @return the number of instances
*/
long count(Specification<T> spec);
}

我项目上使用到的实例:

public Page<TestBean> specificationFind(Integer size, Integer page, TestBean test) {
Field[] fields = CreditsEventBean.class.getDeclaredFields(); //通过反射获取实体类的所有属性
Sort sort = new Sort(Direction.ASC, "sort").and(new Sort(Direction.DESC, "cutOffTime"));//排序规则 多条件
Pageable pageable = new PageRequest(page-1, size, sort);//分页
return activityDao.findAll(new Specification<CreditsEventBean>() {// Page<T> findAll(Specification<T> spec, Pageable pageable); 分页加多态查询
@SuppressWarnings("unchecked")//压制警告
@Overridepublic Predicate toPredicate(Root<CreditsEventBean> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Map<String, Object> conditions = null;
try {
conditions = BeanUtils.describe(event);//使用Apache的工具类将实体转换成map
conditions.remove("sort");//去掉某些用不到的字段 比如排序字段等
conditions.remove("maxPlayers");// } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
System.err.println("specificationFind ---bean转map出错");
}
List<Predicate> predicates = new ArrayList<>();//存储查询语句
for (int i = 0; i < fields.length; i++) {//循环bean的所有属性
fields[i].setAccessible(true);//是否允许访问
String name = fields[i].getName();//获取属性名
if(conditions.containsKey(name)) {//查询这个键是否存在与这个属性中
if(ObjectUtils.isEmpty(conditions.get(name))) {//判断这个键的值是否为空
continue;//结束本次循环,进入下一次循环
}
if(name.equals("creditStatus")||name.equals("activityShop")
||name.equals("isShopEvent")||name.equals("isPutaway")) {//这里 等于条件
predicates.add(cb.equal(root.get(name), conditions.get(name)));
                
注意:如果查询的表中有关联的表,可能会报错
原因:可能是bean转map的时候,BeanUtils.describe方法将关联bean没取出来,只是取了关联bean的内存地址并存储为字符串,导致关联bean的数据消失 暴力解决方法:
if(name.equals("关联Bean")) {
predicates.add(cb.equal(root.get(name),filed.get关联Bean()));
}else {
predicates.add(cb.equal(root.get(name), conditions.get(name)));
}

continue;
}else if(name.equals("activityStartCreditsDT")||name.equals("activityEndCreditsDT")
||name.equals("creteateTime")||name.equals("cutOffTime")) {// 这里是between条件
String value = (String) conditions.get(name);
String[] split = value.split(",");//分割
predicates.add(cb.between(root.get(name), split[0], split[1]));
continue; }
predicates.add(cb.like(root.get(name), "%"+conditions.get(name)+"%"));// 这里是 模糊 条件
}
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));//返回结果集
}
}, pageable); }

CriteriaBuilder主要api:

等!

spring jpa 动态查询(Specification)的更多相关文章

  1. spring JPA 动态查询

    没什么好说的,记住就行. 下面是在Service中的方法 Page<TStaff> staffs=dao.findAll(new Specification<TStaff>() ...

  2. Spring JPA 定义查询方法

    Spring JPA 定义查询方法 翻译:Defining Query Methods ​ 存储库代理有两种方式基于方法名派生特定域的查询方式: 直接从方法名派生查询 自定义查询方式 ​ 可用选项基于 ...

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

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

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

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

  5. spring jpa 自定义查询数据库的某个字段

    spring jpa 提供的查询很强大, 就看你会不会用了. 先上代码, 后面在解释吧 1. 想查单个表的某个字段 在repository中 @Query(value = "select i ...

  6. JPA动态查询封装

    一.定义一个查询条件容器 /** * 定义一个查询条件容器 * * @param <T> */ public class Criteria<T> implements Spec ...

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

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

  8. Spring Data Jpa (二)JPA基础查询

    介绍Spring Data Common里面的公用基本方法 (1)Spring Data Common的Repository Repository位于Spring Data Common的lib里面, ...

  9. Hibernate JPA 动态criteria语句针对null查询条件的特殊处理

    最近原Hibernate项目需要添加一个条件,结构有点类似下面的格式,学生和房间是多对一的关系,现在要查询所有没有房间的学生. Class Student{ @ManyToOne Room room; ...

随机推荐

  1. Bugku-CTF之flag在index里

      Day15 flag在index里 http://123.206.87.240:8005/post/      

  2. Spring错误——Spring AOP——org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException

    背景:学习切面,测试前置通知功能,xml配置如下 <?xml version="1.0" encoding="UTF-8"?> <beans ...

  3. Qt基础学习---滑动条之QSlider

    Qt滑动条基本用法: //mydialog.h #ifndef MYDIALOG_H #define MYDIALOG_H #include <QDialog> class QLineEd ...

  4. 【Python】【自动化测试】【pytest】【常用命令行选项】

    https://www.cnblogs.com/cnkemi/p/9989019.html http://www.cnblogs.com/cnkemi/p/10002788.html pytest 常 ...

  5. 元注解——java.lang.annotation.Target(1.8)

    参考资料:https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Target.html 普通注解’只能用来注解’代码’,而’元注 ...

  6. P1325 雷达安装

    传送门 思路: 采取贪心的思想. 把每个岛屿看作圆心,以雷达的范围 d 为半径,求出与 x 轴的左右两个交点,两交点所夹的区间就需要放置一个雷达,这样就把这道题转换为了区间取点问题.在枚举岛屿时,记录 ...

  7. 表单提交:button input submit 的区别

    http://harttle.com/2015/08/03/form-submit.html 最近项目代码中的表单提交的方式已经百花齐放了,现在用这篇文章来整理一下不同表单提交方式的区别,给出最佳实践 ...

  8. JavaEE XML的读写(利用JDom对XML文件进行读写)

    1.有关XML的写 利用JDom2包,JDom2这个包中,至少引入org.jdom2.*;如果要进行XML文件的写出,则要进行导入org.jdom2.output.*; package com.lit ...

  9. java笔记 -- java简单结构代码解析及注释

    结构代码解析 public class FirstSample { public static void main(String[] args) { System.out.println(2.0-1. ...

  10. 雷林鹏分享:jQuery EasyUI 数据网格 - 扩展编辑器

    jQuery EasyUI 数据网格 - 扩展编辑器 一些常见的编辑器(editor)添加到数据网格(datagrid),以便用户编辑数据. 所有的编辑器(editor)都定义在 $.fn.datag ...