I want to query my "customers" table using "name + surname" string as a key.
Name and surname are stored in different fields.
So my query would be:
SELECT
*
FROM
customers
WHERE
CONCAT(name,' ',surname) LIKE '%term%'
OR CONCAT(surname,' ',name) LIKE '%term%'
However, I can't do that, my query is a JPA2 criteria query. Something like:
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root<Customer> from = cq.from(Customer.class);
cq.select(from);
Predicate whereClause = cb.or(
cb.like(from.<String>get("name"), "%"+ r +"%"),
cb.like(from.<String>get("surname"), "%"+ r +"%"),
);
cq.where(whereClause);
TypedQuery<Customer> query = getEntityManager().createQuery(cq);
list = query.getResultList();
How can I filter my result set by the combination of name and surname, please?
Use CriteriaBuilder.concat(Expression, Expression):
Expression<String> exp1 = cb.concat(from.<String>get("name"), " ");
exp1 = cb.concat(exp1, from.<String>get("surname"));
Expression<String> exp2 = cb.concat(from.<String>get("surname"), " ");
exp2 = cb.concat(exp2, from.<String>get("name"));
Predicate whereClause = cb.or(cb.like(exp1, "%"+ r +"%"), cb.like(exp2, "%"+ r +"%"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With