这适用于
@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 默认将字符串绑定(bind)为VARCHAR
。这里的廉价解决方案是使用 cast(s):
details @> CAST(:details AS jsonb)
但是,如果你有很多查询,其中一些非标准类型被用作参数并且你想绑定(bind)它们的字符串表示,你可以使用
stringtype=unspecified
JDBC DSN parameter在你的连接字符串中。这样,由 setString()
绑定(bind)的每个参数在 PostgreSQL 中都会有一个 unknown
类型,因此它将尝试推断它们的实际类型。
关于java - 在 nativeQuery 中注入(inject) JSON 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683728/