简体   繁体   English

在 nativeQuery 中注入 JSON 参数

[英]Injecting JSON parameter in nativeQuery

This works when这适用于

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

I am passing @Param("schoolId") String schoolId我正在传递@Param("schoolId") String schoolId

But when I pass the JSON as a param, it fails with但是当我将 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 binds Strings as VARCHAR by default. Spring+JDBC 默认将字符串绑定为VARCHAR The cheap solution here is to use cast(s):这里的廉价解决方案是使用演员表:

details @> CAST(:details AS jsonb)

But, if you have a lot of queries, in which some non-standard types are used as parameters & you want to bind their String representation, you can use the但是,如果你有很多查询,其中一些非标准类型被用作参数并且你想绑定它们的字符串表示,你可以使用

stringtype=unspecified

JDBC DSN parameter in your connection string.连接字符串中的JDBC DSN 参数 That way, every parameter, which is bound by setString() will have an unknown type in PostgreSQL, thus it will try to infer their actual types.这样,每个被setString()绑定的参数在 PostgreSQL 中都会有一个unknown类型,因此它会尝试推断它们的实际类型。

Thanks for this.谢谢你。

Just in addition to the solution, you can also do the cast as:除了解决方案之外,您还可以执行以下转换:

details @> :details::jsonb

I'm using version 11 of postgres, not sure when it was introduced.我正在使用 postgres 的 11 版,不确定它是什么时候推出的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM