java - 在 nativeQuery 中注入(inject) JSON 参数

标签 java spring postgresql spring-data-jpa jsonb

这适用于

@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/

相关文章:

java - 从字符串数组+颜色词中获取每个单词

java - Spring 工具套件 - SunCertPathBuilderException : unable to find valid certification path to requested target

sql - 查找连续模式(使用 SQL)

javascript - 如何查询 postgres 数据库中现有的电子邮件

JavaFX Maven jfx :jar error: Could not find artifact javafx-packager

java - IntelliJ IDEA 无法打开 *.cfg 文件

java - Runnable抛出异常可以用Lambda代替吗?

java - eclipse中的spring petclinic编译错误

java - 在 JUnit 测试期间动态更改 bean 范围

postgresql - 如何为Docker容器公开几个端口?