2017-03-08 109 views
0

这工作时注浆JSON参数 - 春天JPA

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

我传递@Param( “schoolId”)字符串schoolId

但是当我通过JSON作为PARAM,它失败

"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

+0

请向我们展示真正的异常,这是''SQLGrammarException'(它在原因链的末尾)造成的。我们只能猜测没有它。 - 但我最好的选择是spring + jdbc将'@Param(“details”)字符串细节参数绑定为'VARCHAR'。如果你想使用一些非常规的类型,比如'uuid'或'json [b]',通常很难使用JDBC。只需在连接字符串中添加'stringtype = unspecified' [JDBC DSN参数](https://jdbc.postgresql.org/documentation/head/connect.html#connection-parameters)就可以避免很多麻烦。 – pozs

+0

......或者你可以使用明确的转换,比如'details @> CAST(:details AS json [b])'',但这是很不愉快的恕我直言。 – pozs

+0

@pozs你是正确的,它确实工作后,它被称为CAST(:细节AS JSONB)。如果您可以发布相同的答案,我会接受并解决问题。 –

回答

1

默认情况下,Spring + JDBC将字符串绑定为VARCHAR。这里的廉价的解决方案是采用CAST(S):

details @> CAST(:details AS jsonb) 

但是,如果你有很多疑问,其中一些不规范的类型被用作&要绑定的字符串表示的参数,你可以在您的连接字符串中使用

stringtype=unspecified 

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