代码之家  ›  专栏  ›  技术社区  ›  yaswanth

当使用fetchOne时,jooq抛出NPE

  •  3
  • yaswanth  · 技术社区  · 7 年前

                dslContext.select(XXX.NAME)
                    .from(XXX)
                    .where(
                        XXX.ID.eq(id)
                            .and(XXX.LEVEL.eq(2))
                            .and(XXX.NAME.isNotNull())
                    )
                    .fetchOne().into(String.class);
    

    在我的例子中,对于一个特定的id,查询结果是一个空集。但jooq似乎抛出了一个NPE。当我进一步调查时, fetchOne() 电话 CursorImpl.fetchOne() into(String.class)

    org.jooq.exception.NoDataFoundException 如果没有数据?

    1 回复  |  直到 7 年前
        1
  •  8
  •   Lukas Eder    7 年前

    为什么a NullPointerException 正在被抛出

    从技术上讲,jOOQ不会抛出 .你的使命 into(Class) 在潜在的 null 如的Javadoc中所述 ResultQuery.fetchOne()

    返回:
    如果查询未返回任何记录,则返回结果记录或null。

    投掷 NoDataFoundException .

    fetchOptional() 然后使用 orElseThrow() :

    String string =
    dslContext.select(XXX.NAME)
        .from(XXX)
        .where(
            XXX.ID.eq(id)
                .and(XXX.LEVEL.eq(2))
                .and(XXX.NAME.isNotNull())
        )
        .fetchOptional()
        .orElseThrow(() -> new NoDataFoundException("..."))
        .into(String.class);
    

    https://github.com/jOOQ/jOOQ/issues/5411

    String string =
    dslContext.select(XXX.NAME)
        .from(XXX)
        .where(
            XXX.ID.eq(id)
                .and(XXX.LEVEL.eq(2))
                .and(XXX.NAME.isNotNull())
        )
        .fetchSingle() // Might throw a NoDataFoundException but never returns null
        .into(String.class);