的用法?在 jsonb 上的本机 SQL 查询中

Usage of ? in native SQL query on jsonb

我需要针对 Postgres jsonb 列发起 select 查询:

entityManager.createNativeQuery(
 "select * from table where jsonbcol -> 'usernames' ? :un"
).setParameter("un", userName).getResultList()

在 运行 时抛出异常:

org.hibernate.engine.query.ParameterRecognitionException: Mixed parameter strategies - 
use just one of named, positional or JPA-ordinal strategy

我试过像 \??? 那样转义,但没有用。

如何正确调用?

正如the documentation所说:

In JDBC, the question mark (?) is the placeholder for the positional parameters of a PreparedStatement. There are, however, a number of PostgreSQL operators that contain a question mark. To keep such question marks in a SQL statement from being interpreted as positional parameters, use two question marks (??) as escape sequence.

有一个替代解决方案可以证明是一个优雅的解决方法。 Postgres 运算符 ? 是基于 jsonb_exists() 函数的,所以不用

where jsonbcol -> 'usernames' \?\? :un

你可以使用

where jsonb_exists(jsonbcol -> 'usernames', :un)

正确的转义序列使得查询如下:

entityManager.createNativeQuery(
 "select * from table where jsonbcol -> 'usernames' \?\? :un"
).setParameter("un", userName).getResultList()

反斜杠转义hibernate参数检测,两个问号是JDBC转义