5

我想使用“name + surname”字符串作为键来查询我的“customers”表。

姓名和姓氏存储在不同的字段中。

所以我的查询是:

SELECT 
   * 
FROM 
   customers 
WHERE 
   CONCAT(name,' ',surname) LIKE '%term%' 
   OR CONCAT(surname,' ',name) LIKE '%term%' 

但是,我不能这样做,我的查询是 JPA2标准查询。就像是:

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

请问如何通过姓名和姓氏的组合过滤我的结果集?

4

1 回答 1

21

使用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 +"%"));
于 2013-03-19T16:01:51.163 回答