spring jpa 动态查询(Specification)
//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)的更多相关文章
- spring JPA 动态查询
没什么好说的,记住就行. 下面是在Service中的方法 Page<TStaff> staffs=dao.findAll(new Specification<TStaff>() ...
- Spring JPA 定义查询方法
Spring JPA 定义查询方法 翻译:Defining Query Methods 存储库代理有两种方式基于方法名派生特定域的查询方式: 直接从方法名派生查询 自定义查询方式 可用选项基于 ...
- springboot整合spring data jpa 动态查询
Spring Data JPA虽然大大的简化了持久层的开发,但是在实际开发中,很多地方都需要高级动态查询,在实现动态查询时我们需要用到Criteria API,主要是以下三个: 1.Criteria ...
- spring data jpa 动态查询(工具类封装)
利用JPA的Specification<T>接口和元模型就实现动态查询了.但是这样每一个需要动态查询的地方都需要写一个这样类似的findByConditions方法,小型项目还好,大型项目 ...
- spring jpa 自定义查询数据库的某个字段
spring jpa 提供的查询很强大, 就看你会不会用了. 先上代码, 后面在解释吧 1. 想查单个表的某个字段 在repository中 @Query(value = "select i ...
- JPA动态查询封装
一.定义一个查询条件容器 /** * 定义一个查询条件容器 * * @param <T> */ public class Criteria<T> implements Spec ...
- Spring Data JPA动态查询(多条件and)
entity: @Entity @Table(name = "data_illustration") public class Test { @Id @GenericGenerat ...
- Spring Data Jpa (二)JPA基础查询
介绍Spring Data Common里面的公用基本方法 (1)Spring Data Common的Repository Repository位于Spring Data Common的lib里面, ...
- Hibernate JPA 动态criteria语句针对null查询条件的特殊处理
最近原Hibernate项目需要添加一个条件,结构有点类似下面的格式,学生和房间是多对一的关系,现在要查询所有没有房间的学生. Class Student{ @ManyToOne Room room; ...
随机推荐
- kvm日常维护
1.列出物理机器上安装的虚拟[root@localhost ~]# virsh list --all Id Name State------------------------------------ ...
- rest_framework视图和组件
一.视图 1.基本视图 #基本视图 #抽取基类 from rest_framework.response import Response from rest_framework.views impor ...
- NPOI解决由于excel删除数据导致空行读取问题
1.解决问题思路一:申明判断是否空行变量用于判断是否空行,声明变量数组用于临时非空行数据,最后存于datatable中. /// <summary>读取excel, /// 默认第一行为表 ...
- CMD控制器常用命令
dir 查看当前路径文件cd..返回上一级路径cd 转到指定的文件夹 \n 将光标移动到下一行的第一格 \t 将光标移动到下一个水平制表位置 mspaint 画图 编译源代码 javac HelloW ...
- [BZOJ2298]problem a
Description 一次考试共有n个人参加,第i个人说:“有ai个人分数比我高,bi个人分数比我低.”问最少有几个人没有说真话(可能有相同的分数) Input 第一行一个整数n,接下来n行每行两个 ...
- Learning-Python【14】:匿名函数与函数递归
一.什么是匿名函数 匿名函数就是没有名字的函数,又叫lambda表达式.用于一些简单的需要用函数去解决的问题,特点是只能在定义时使用一次,且函数体只有一行 匿名函数的定义就相当于只产生一个变量的值,而 ...
- MSSQL 数据库 buildindex 出错
错误1: Executing the query "ALTER INDEX [IX_liveConfigState_Service_ServiceId_..." failed wi ...
- Java核心技术梳理-泛型
一.引言 在学习集合的时候我们会发现一个问题,将一个对象丢到集合中后,集合并不记住对象的类型,统统都当做Object处理,这样我们取出来再使用时就得强制转换类型,导致代码臃肿,而且加入集合时都是以Ob ...
- 二叉树放置照相机 Binary Tree Cameras
2019-03-27 15:39:37 问题描述: 问题求解: 很有意思的问题,问题描述简单,求解过程也可以非常的简洁,是个难得的好题. 求解的过程是自底向上进行分析,对于叶子节点,如果在叶子上放置照 ...
- 码云git使用五(创建远程分支和更新远程分支)
1.创建一个与远程分支没有关联的本地分支 2.从远程拉取到本地分支 3.创建远程分支() 4.搞定了.