Querydsl null-safe concatenation

若如初见. 提交于 2020-01-03 18:53:32

问题


Suppose you have the following data in table corresponding to the class Person, what is the correct way to search null-safely for the concatenation of fields name1 and name2?

@Entity
public class Person {
    Long id;
    String name1;
    String name2;
    // Getters and setters omitted for brevity
}
id |  name1  | name2   
------------------------
1  |  Foo    | null
2  |  null   | Bar
3  |  Foo    | Bar

By default the concatentation of two columns results in null if either is null.

public List<String> nameConcatenations() {
    JPAQuery q = new JPAQuery(entityManager);
    QPerson person = QPerson.person;
    StringExpression nameConcatenation = person.name1.concat(person.name2);
    return q.from(person).list(nameConcatenation)
}

The above code results in the following list:

null
null
FooBar

回答1:


One easy way is to use the SQL's COALESCE function which has an equivalent in Querydsl

public List<String> nameConcatenations() {
    JPAQuery q = new JPAQuery(entityManager);
    QPerson person = QPerson.person;
    StringExpression nameConcatenation = emptyIfNull(person.name1)
        .concat(emptyIfNull(person.name2));
    return q.from(person).list(nameConcatenation)
}

private static StringExpression emptyIfNull(StringExpression expression) {
    return expression.coalesce("").asString();
}

Will result in the following list:

Foo
Bar
FooBar


来源:https://stackoverflow.com/questions/14977812/querydsl-null-safe-concatenation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!