如果字段为空,则 Jooq fetchInto 使用默认值 [英] Jooq fetchInto with default value if field is null
问题描述
我有数据类
data class Author(
val id: String,
val name: String,
val books: MutableList<Book> = mutableListOf()
) {}
我用 jooq 写了请求
And I wrote request using jooq
val resultSet = dsl.select(author.ID, author.NAME,
field(select(jsonArrayAgg(jsonObject(book.ID, book.PRICE)))
.from(books)
.where(book.AUTHOR_ID.eq(author.ID))
).`as`("books"))
.from(authors)
.fetchInto(Author::class.java)
但是如果作者没有书,我会得到一个例外.这是合乎逻辑的,因为数据类 Author 中的字段书籍不可为空.我试图将伴随对象添加到数据类
But I get an exception if Author has no books. It is logical, because field books in data class Author is not nullable. I tried to add companion object to data class
companion object {
operator fun invoke(
id: String,
name: String,
books: MutableList<Book>? = null
) = Author(id, name, books ?: mutableListOf())
}
但是它不起作用,jooq 仍然尝试使用默认构造函数并且我得到一个异常.有没有办法在不使数据类 Author 中的外地手册可以为空的情况下修复它?
But it doesn't work, jooq still tries to use default constructor and I get an exception. Is there a way to fix it without making field books in data class Author nullable?
推荐答案
原因是 JSON_ARRAYAGG()
(像大多数聚合函数一样)为空集产生 NULL
,而不是更合理"的空 []
.显然,你永远不想要这种行为.所以,你可以使用COALESCE
,而另见这个问题:
The reason is that JSON_ARRAYAGG()
(like most aggregate functions) produces NULL
for empty sets, instead of a more "reasonable" empty []
. Clearly, you never want this behaviour. So, you could use COALESCE
, instead, see also this question:
coalesce(
jsonArrayAgg(jsonObject(book.ID, book.PRICE)),
jsonArray()
)
我会确保更新我在 Stack Overflow 上给出的所有其他答案以指出这一点.未来的 jOOQ 版本可能会提供 NULL
安全的聚合函数,以防存在聚合的合理标识(例如 []
)以使其更容易被发现:https://github.com/jOOQ/jOOQ/issues/11994
I'll make sure to update all the other answers I've given on Stack Overflow to point this out. A future jOOQ version might offer NULL
safe aggregate functions in case there exists a reasonable identity for aggregation (e.g. []
) to make this more discoverable: https://github.com/jOOQ/jOOQ/issues/11994
这篇关于如果字段为空,则 Jooq fetchInto 使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!