Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Expression concatenate more than two columns

I have the following statement to concatenate two columns which works well

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

and SQL is

select emp.user_id|| ' # '|| dept.emp_name from ..       

I would like to concatenate one more column and SQL is

select emp.user_id|| ' # '|| dept.emp_name|| ' # '|| hist.user_name from ..       

Not sure how add other columns in JPA API using CriteriaBuilder and Expression

Edit 1

I am looking for concatenation using multiple columns and answer which is marked as duplicate doesn't help to resolve the problem and most importantly this question is tagged and seeking solution to resolve concatenation issue pertains to JPA Criteria API and certainly not JPQL.

like image 556
Jacob Avatar asked Nov 25 '15 12:11

Jacob


1 Answers

You can basically wrap the concat(...) into each other, or use a method like the following (assuming you want to use the same delimiter string between columns):

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);
like image 196
jabu.10245 Avatar answered Dec 08 '22 08:12

jabu.10245