Search code examples
javadatabasenulldata-access-layerquerydsl

Querydsl null-safe concatenation


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

Solution

  • 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