gpt4 book ai didi

JPA 表达式连接多于两列

转载 作者:行者123 更新时间:2023-12-04 12:40:09 26 4
gpt4 key购买 nike

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

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

和 SQL 是
select emp.user_id|| ' # '|| dept.emp_name from ..       

我想再连接一列,SQL 是
select emp.user_id|| ' # '|| dept.emp_name|| ' # '|| hist.user_name from ..       

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

编辑 1

我正在寻找使用多列的连接,标记为重复的答案无助于解决问题,最重要的是,这个问题被标记并寻求解决连接问题的解决方案与 JPA Criteria API 有关,当然不是 JPQL。

最佳答案

你基本上可以把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);

关于JPA 表达式连接多于两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33916045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com