【问题标题】:QueryDsl, elegant way to make method cascades NULL safe with Java or GroovyQueryDsl,使用 Java 或 Groovy 使方法级联 NULL 安全的优雅方式
【发布时间】:2013-04-22 13:05:01
【问题描述】:

如果在遍历可能为空的级联方法时经常遇到 NPE。例如,我想查询客户的“称呼”属性..

     ConstructorExpression giftCE = ConstructorExpression.create(Gift,
            order.a.b.c.salutation
    )

任何或所有 a、b 或 c 都可能为 NULL,从而导致 NPE。

在 Java 或 Groovy 中防范此类 NPE 的最佳“querydsl”方式是什么?

(我不确定 Groovy 的 Elvis op 是否在 querydsl 语句中涵盖了这种情况)

【问题讨论】:

    标签: methods groovy nullpointerexception querydsl cascading


    【解决方案1】:

    您可以使用字段访问器而不是最终字段。这样你就不会遇到 NPE http://www.querydsl.com/static/querydsl/3.1.1/reference/html/ch03s04.html#d0e1713

    我不确定您是否可以在 Groovy 中通过字段/属性语法使用它们,因为它们不是 getter。

    在你的情况下它会变成

    ConstructorExpression giftCE = ConstructorExpression.create(Gift,
        order.a().b().c().salutation
    )
    

    【讨论】:

    • 我猜 ConstructorExpression.create 严格拒绝属性为空。因此,即使我在某一点使用 Will Ps 解决方案或另一个 order.a.b.c.salutation 本身可能为 null,这会导致 com.mysema.query.types.ConstructorExpression.create(ConstructorExpression.java:79) 处的 java.lang.NullPointerException
    • 是的,空参数是无效的,在你的情况下也不是真的想要。
    猜你喜欢
    • 2013-11-14
    • 2020-10-09
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多