gpt4 book ai didi

java - 如何使用 R2dbc 将 jsonb 从 Postgresql 提取到 Spring webflux

转载 作者:行者123 更新时间:2023-12-02 09:31:22 24 4
gpt4 key购买 nike

所以我有这个想法,这真的超出了我的想象,因为我只编程了很短一段时间,但我想构建一个响应式(Reactive) Spring webflux 应用程序,将 json 端点公开给 react 前端。

当我决定在 Postgres 中使用 jsonb 格式时,问题就开始了,因为我认为我可能会从数据库一直到前端层一直使用 json。

当我尝试使用响应式(Reactive) R2dbc 驱动程序使用 jsonb 来选择表时,出现以下错误:

Caused by: java.lang.IllegalArgumentException: 3802 is not a valid object id

我在 postgres 中有一个表,如下所示:

Column  |  Type   | Collation | Nullable |           Default
---------+---------+-----------+----------+------------------------------
id | integer | | not null | generated always as identity
details | jsonb | | |
Indexes:
"snacks_new_pkey" PRIMARY KEY, btree (id)

因此,如果我将其作为文本提取到 Spring webflux,它就可以正常工作,因为它不再是 json。

"SELECT id, details->>'name' as NAME, details->>'price' AS PRICE, details->>'quantity' AS QUANTITY FROM snacks_new"

我已经看到了一些关于如何使用旧的阻塞驱动程序将 jsonb 转换为 json 对象的示例,但我无法将其与较新的非阻塞驱动程序一起使用,我无法以任何方式访问它们.

所以我真的有两个问题,我如何使用响应式(Reactive)驱动程序选择一个包含 jsonb 的表,我是否在浪费时间尝试这样做,将 json 提取为文本并从中创建一个普通的 POJO 就足够了?

感谢您的宝贵时间!

最佳答案

更新:请升级到 R2DBC Postgres 0.8.0.RC1。

驱动程序已添加recently支持 JSON 和 JSONB 类型。您可以将 JSON 作为 Stringbyte[]io.r2dbc.postgresql.codec.Json 类型使用:

// Read as Json
connection.createStatement("SELECT my_json FROM my_table")
.execute()
.flatMap(it -> it.map((row, rowMetadata) -> row.get("my_json", Json.class)))
.map(Json::asString)

// Read as String
connection.createStatement("SELECT my_json FROM my_table")
.execute()
.flatMap(it -> it.map((row, rowMetadata) -> row.get("my_json", String.class)))

// Write JSON
connection.createStatement("INSERT INTO my_table (my_json) VALUES($1)")
.bind("$1", Json.of("{\"hello\": \"world\"}"))
.execute()

// Write JSON as String using ::JSON casting
connection.createStatement("INSERT INTO my_table (my_json) VALUES($1::JSON)")
.bind("$1", "{\"hello\": \"world\"}")
.execute()

请注意,当您想要为 SELECTINSERTUPDATE 绑定(bind) JSON 值时,您必须使用驱动程序 Json 使用 $1::JSON 键入或将绑定(bind)值转换为 JSON。

您还可以利用驱动程序的 CodecRegistrar 提供您自己的 JsonCodec 实现,如果您想要使用 GSON 或 Jackson 在驱动程序级别映射序列化/反序列化值。

引用文献:

关于java - 如何使用 R2dbc 将 jsonb 从 Postgresql 提取到 Spring webflux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57942240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com