我想使用“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();
如何通过名称和姓氏的组合过滤我的结果集?
答案 0 :(得分:14)
使用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 +"%"));