首页 > 解决方案 > 使用 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;

当我运行这个方法时,我总是得到一个空列表。我尝试通过给我一个包含与给定搜索文本不同的元素的列表来更改liketonotLike并且效果很好,所以我真的很困惑我的like方法有什么问题。任何形式的帮助将不胜感激!

标签: jpaejbjpqljava-ee-6criteriaquery

解决方案


当我进行一些测试并在类路径中有具有相同(简单)名称的实体时,我遇到了类似的问题。例如,有如下实体:

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);

推荐阅读