jpa - 使用 Criteria Builder 对多列进行 JPA 搜索查询
问题描述
我正在尝试使用标准构建器对我的实体进行通用搜索,其中给定的文本与实体中的所有列匹配。
String likeSearchText = "%" + searchText + "%";
List<Customer> searchedCustomers = null;
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery(Customer.class);
Root <Customer> root = query.from(Customer.class);
ArrayList<Predicate> conditions = new ArrayList<>();
conditions.add(builder.like(root.<String>get("firstName"), likeSearchText));
conditions.add(builder.like(root.<String>get("lastName"), likeSearchText));
conditions.add(builder.like(root.<String>get("middleName"), likeSearchText));
conditions.add(builder.like(root.<String>get("companyName"), likeSearchText));
conditions.add(builder.like(root.<String>get("industry"), likeSearchText));
query.where(builder.or(conditions.toArray(new Predicate[conditions.size()])));
query.select(root);
searchedCustomers = entityManager.createQuery(query).getResultList();
return searchedCustomers;
当我运行这个方法时,我总是得到一个空列表。我尝试通过给我一个包含与给定搜索文本不同的元素的列表来更改like
tonotLike
并且效果很好,所以我真的很困惑我的like
方法有什么问题。任何形式的帮助将不胜感激!
解决方案
当我进行一些测试并在类路径中有具有相同(简单)名称的实体时,我遇到了类似的问题。例如,有如下实体:
org.example.one.Customer
org.example.two.Customer
如果您没有明确设置不同的表名,例如:
package org.example.one;
@Entity("customer_one")
public class Customer { ...
和
package org.example.two;
@Entity("customer_two")
public class Customer { ...
休眠可能:
- 在 db 的同一张表中混合内容
- 构造查询时尝试从错误的表中查找字段
我也认为你不需要这个:
query.select(root);
推荐阅读
- javascript - 更新切片中的状态,将对象作为有效负载
- android - ANDROID STUDIO - 如何将标记添加到当前位置?
- sql - 如何在 MS SQL Server 中使用正则表达式(或等效)来解决这个问题?
- excel - 将 Excel 图表粘贴到 Word 的宏可以工作,但在作为加载项运行时会出错
- r - Modeltime.resample - 为什么 modeltime_fit_resamples() 不接受“未拟合”的 modeltime_table 作为输入?
- python-3.x - Python3如何在触发异常时在for循环中的项目处恢复
- powershell - 循环 Powershell 脚本以每小时重新提示用户或直到达到超时限制
- sql - HIVE 选择日期之间的位置,但它是字符串 YYYYMMDD,而不是数字日期格式?
- mongodb - Spring-Boot:如何检查 Mongock 是否已完成?
- react-native - react-native-gifted-chat 上的渲染方法上未填充上一条消息