【问题标题】:JPA query filter on concatenated fields连接字段上的 JPA 查询过滤器
【发布时间】:2013-03-08 08:57:44
【问题描述】:

我想使用“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();

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

【问题讨论】:

    标签: hibernate jpa jpa-2.0 criteria-api


    【解决方案1】:

    使用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 +"%"));
    

    【讨论】:

    • 如果您的数据库支持 CONCAT_WS(带分隔符的连接),您可以执行以下操作: Expression nameConcat = cb.function( "CONCAT_WS", String.class, cb.literal(" ") , from.get("name"), from.get("surname"));我想在我的 concat 中有一个分隔符,但是有些字段是空的或 null 并且将它们链接在一起会在我的 concat 中添加空格,这是我在有空格时不想要的。
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多