JPA Expression连接两列以上

Jåc*_*cob 7 jpa criteria eclipselink criteria-api jpa-2.0

我有以下语句来连接两个效果很好的列

Expression<String> stringConcat = 
            cb.concat(cb.concat(root.get(Employee_.userId), " # "), 
                                   joinDept.get(Employee_.empName));
Run Code Online (Sandbox Code Playgroud)

和SQL是

select emp.user_id|| ' # '|| dept.emp_name from ..       
Run Code Online (Sandbox Code Playgroud)

我想再连接一个列和SQL

select emp.user_id|| ' # '|| dept.emp_name|| ' # '|| hist.user_name from ..       
Run Code Online (Sandbox Code Playgroud)

不确定如何使用CriteriaBuilder和Expression在JPA API中添加其他列

编辑1

我使用多列,并且被标记为重复的答案无助于解决问题,最重要的这个问题被标记,并寻求解决方案来解决问题拼接属于JPA标准API,当然不是JPQL寻找串联.

jab*_*245 3

您基本上可以将它们concat(...)相互包装起来,或者使用如下方法(假设您想在列之间使用相同的分隔符字符串):

private CriteriaBuilder criteriaBuilder = /* ... */

// notice the three dots before "expressions", they are no decoration ;-)
private Expression<String> concat(String delimiter, Expression<String> ... expressions) {
    Expression<String> result = null;
    for (int i = 0; i < expressions.length; i++) {
        final boolean first = i == 0, last = i == (expressions.length - 1);
        final Expression<String> expression = expressions[i];
        if (first && last) {
            result = expression;
        } else if (first) {
            result = criteriaBuilder.concat(expression, delimiter);
        } else {
            result = criteriaBuilder.concat(result, expression);
            if (!last) {
                result = criteriaBuilder.concat(result, delimiter);
            }
        }
    }
    return result;
}

Expression<String> userId = root.get(Employee_.userId);
Expression<String> empName = joinDept.get(Employee_.empName);
Expression<String> userName = hist.get(User_.name); // or whatever

Expression<String> stringConcat = concat(" # ", userId, empName, userName);
Run Code Online (Sandbox Code Playgroud)