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

标签 java postgresql spring-webflux jsonb r2dbc

所以我有这个想法,这真的超出了我的想象,因为我只编程了很短一段时间,但我想构建一个响应式(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/

相关文章:

java - 如何关闭 p :password? 的重新显示

java - 隐形JFrame/JTable 快多少?

java - Maven多模块依赖问题

c# - 在旧的 ascii postgresql 数据库中使用 npgsql entityFrameworkCore 的编码问题

javascript - Node.js 和 Node-Postgres : Putting Queries into Models

java - 仅当Mono为空时如何执行操作并抛出不为空的错误

netty - 将 spring-webflux 微服务切换到 http/2 (netty)

java - 在 main() 方法中使用断言

asp.net - 如果 PostgreSql 数据库中的数据发生更改,如何使 ASP.NET 缓存失效

Spring WebClient Post 方法体