在 nativeQuery 中注入 JSON 参数

Injecting JSON parameter in nativeQuery

这在

时有效
@Query(
  value = "SELECT * FROM person WHERE school = :schoolId AND details @> '{\"id\":\"1234\",\"name\":\"John\"}'", 
  nativeQuery = true
)

我路过@Param("schoolId") String schoolId

但是当我将 JSON 作为参数传递时,它失败并显示

org.springframework.dao.InvalidDataAccessResourceUsageException, could not extract ResultSet; SQL [n/a]; nested exception is 
org.hibernate.exception.SQLGrammarException: could not extract ResultSet

org.postgresql.util.PSQLException: ERROR: operator does not exist: jsonb @> character varying
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

@Query(value = "SELECT * FROM person WHERE school = :schoolId AND details @> :details", nativeQuery = true)

@Param("schoolId") String schoolId, @Param("details") String details
默认情况下,

Spring+JDBC 将字符串绑定为 VARCHAR。这里的廉价解决方案是使用 cast(s):

details @> CAST(:details AS jsonb)

但是,如果你有很多查询,其中一些非标准类型被用作参数并且你想绑定它们的字符串表示,你可以使用

stringtype=unspecified

JDBC DSN parameter 在您的连接字符串中。这样,每个由 setString() 绑定的参数在 PostgreSQL 中都会有一个 unknown 类型,因此它将尝试推断它们的实际类型。

谢谢。

除了解决方案之外,您还可以将其强制转换为:

details @> :details::jsonb

我使用的是 postgres 版本 11,不确定它是什么时候引入的。