4

I'm trying to create a query using CriteriaBuilder where I need to have a predicate where the value of the predicate is like the value in the database.

Basically, I need to be able to do the following: WHERE myTestValue LIKE columnValue

In native queries, it is an option to do that, but using the CriteriaBuilder or NamedQueries, it does not seem to work.

String myValue = "foo@bar.com";
cb.where(cb.like(myValue, root.get(Entity_.email));

Is there an option in JPA to do it like this? Or should I fall back to native queries?

EDIT I need to be able to check if a given value matches a wildcard entry in database. So the database has a record %@bar.com%, and I need to check if my given value foo@bar.com matches to that record.

Erates
  • 646
  • 1
  • 9
  • 24
  • Maybe you have forgot to add "%" at the beginning and at the end of your test string? – perissf Feb 14 '17 at 15:44
  • Do you get any errors? or it just does not work.. – Maciej Kowalski Feb 14 '17 at 16:11
  • It just does not compile. JPA does not like to do it this way ;) – Erates Feb 14 '17 at 16:11
  • 2
    Show what it complains about. You also might first try JPQL to verify it'll work there. If it doesn't like the string, try passing it in as a parameter instead cb.where(cb.like(cb.parameter(String.class, "myValueParameter"), root.get(Entity_.email)); and then set the parameter in the query query.setParameter("myValueParameter", myValue); – Chris Feb 14 '17 at 18:16

2 Answers2

5

I think your params should be other way round:

cb.where(cb.like(root.get(Entity_.email),myValue);

Aditionally you may need to use add this to the second param:

cb.where(cb.like(root.get(Entity_.email),"%"+myValue+"%");
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
2

Chris found the answer. First I need to "generate" a parameter.

ParameterExpression<String> senderEmailParameter = cb.parameter(String.class, "senderEmailParameter");
Path<String> senderEmailPath = root.get(Entity_.senderEmail);

Predicate predEmail = cb.like(senderEmailParameter, senderEmailPath);

And then I need to fill the parameter in the query.

q.where(predEmail);

return em.createQuery(q).setParameter("senderEmailParameter", senderEmail).getSingleResult();

This works! Thanks Chris!

Erates
  • 646
  • 1
  • 9
  • 24