Querydsl空安全串联 [英] Querydsl null-safe concatenation

查看:143
本文介绍了Querydsl空安全串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在表中具有与类 Person 相对应的以下数据,正确地搜索null来安全地搜索字段 name1 和 name2

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

默认情况下,如果任一列为空,则两列的合并将导致 null

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


推荐答案

一种简单的方法是使用SQL的 COALESCE 函数,该函数在Querydsl中是等效的

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();
}

将产生以下列表:

Foo
Bar
FooBar

这篇关于Querydsl空安全串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆