首页 > 解决方案 > 如何在 JPA 中参数化 jsonb_path_query

问题描述

使用 nativeQuery 作为 name_id 属性将参数传递到 jsonb_path_query 的正确语法是什么?

@Query(value = "select jsonb_path_query(columns , '$.names[*] ? (@.name_id == :id && @.is_active == true)' ) -> 'name_id' as name

标签: springpostgresqljpajsonb

解决方案


jsonb_path_query()接受一个额外的 JSONB 参数,该参数可以包含变量作为键/值对。$可以使用JSON 路径中的符号来引用键:

jsonb_path_query(columns , '$.names[*] ? (@.name_id == $id && @.is_active == true)', '{"id": 42}')

jsonb 值可以作为 JDBC 参数传递:

"select jsonb_path_query(columns , '$.names[*] ? (@.name_id == $id && @.is_active == true)', cast(? as jsonb) ) -> 'name_id' as name"

然后,您可以将 String 参数传递"{\"id\": 42}"给查询。

我不知道 JPA,在普通 JDBC 中,这将与PreparedStatement and setString(1, "{"id": 42}")`一起使用


推荐阅读