JPA search query using Criteria Builder for multiple columns

1.5k views Asked by At

I am trying to make a universal search for my entity with criteria builder where a given text is matched with all the columns in the entity.

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;

When I run this method I always get an empty list. I tried changing the like to notLike and that works perfectly fine by giving me a list containing elements which are not like the given search text so I am really confused as to what's wrong with my like method. Any kind of help would be appreciated!

1

There are 1 answers

2
pirho On

I had similar problems when I made some testing and had entities with the same (simple)name in the classpath. So for example there were entities like:

org.example.one.Customer
org.example.two.Customer

If you do not have explicitly set different table names like:

package org.example.one;
@Entity("customer_one")
public class Customer { ...

and

package org.example.two;
@Entity("customer_two")
public class Customer { ...

hibernate might:

  • mix stuff in the same table in db
  • try to find field from wrong table when constructing the query

Also I thibk you do not need this:

query.select(root);