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; ...
随机推荐
- IdentityServer4支持的授权类型以及组合
支持的授权类型: implicit hybrid authorization_code client_credentials password 支持的组合: implicit implicit,cli ...
- 【NOI 2015】品酒大会
Problem Description 一年一度的"幻影阁夏日品酒大会"隆重开幕了.大会包含品尝和趣味挑战两个环节,分别向优胜者颁发"首席品酒家"和" ...
- Windows 启用/禁用内置管理员 Administrator
关于启用 Windows 系统内置的管理员 Administrator 的方法还是许多的,其中普遍的一种应该就是进入(我的电脑/计算机右键管理/Windows + R输入 compmgmt.msc)计 ...
- 启动xampp出错,Port 80 in use by "Unable to open process" with PID 4!
启动xampp出错,Port 80 in use by "Unable to open process" with PID 4! 环境:windows10 80端口被PID为4的应 ...
- Java 中断
https://zhuanlan.zhihu.com/p/45667127 看的似懂非懂
- leecode第一百六十九题(求众数)
class Solution { public: void quick_sort(vector<int>& nums,int res,int res_end) { )//错过,不能 ...
- HihoCoder - 1142 ,三分入门
先来说说三分的思想: 从三分法的名字中我们可以猜到,三分法是对于需要逼近的区间做三等分: 我们发现lm这个点比rm要低,那么我们要找的最小点一定在[left,rm]之间.如果最低点在[rm,right ...
- 佛祖保佑永无BUG代码注释
// // _oo0oo_ // o8888888o // 88" . "88 // (| -_- |) // 0\ = /0 // ___/`---'\___ // .' \\| ...
- 用Eclipse在Weka中嵌入新算法
本文介绍添加一个新算法到Weka集成环境中的过程,并能在GUI中运行并显示其结果.想做到这一点有两种方法,一是用ANT命令生成新的weka.jar(稍后写教程),二是用IDE(Eclipse或NetB ...
- STL 小白学习(2) string
#include <iostream> using namespace std; #include <string> //初始化操作 void test01() { //初始化 ...