Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA query filter on concatenated fields

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?

like image 783
Fabio B. Avatar asked Mar 19 '13 15:03

Fabio B.


1 Answers

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 +"%"));
like image 187
perissf Avatar answered Dec 05 '22 19:12

perissf