我正在尝试在SpRIPDATA本地查询中使用PASGRESJSONB字符串存在操作符。
SpringData方法示例:

@Query(value = "SELECT t.id \n"
        + " FROM task AS t \n"
        + " WHERE (t.worker_ids \\? :workerId)\n"
        + " ORDER BY t.created_at\n",
        nativeQuery = true)
Optional<String> findMatchingTaskId(@Param("workerId") String workerId);

其中worker_ids是数据库中的JSOB类型。
我试图排除带有\\的问号,但仍有以下错误:
org.postgresql.util.PSQLException: No value specified for parameter 2.
有没有办法在spring数据原生查询中使用这个操作符?

最佳答案

PostgreSQL中的所有运算符都使用底层过程:

> SELECT oprname, oprcode FROM pg_operator WHERE oprname LIKE '%?%'

oprname | oprcode
--------------------------
?       | jsonb_exists
?|      | jsonb_exists_any
?&      | jsonb_exists_all
...

因此您可以使用jsonb_exists(jsonb, text)重写查询,如下所示:
SELECT t.id
FROM task AS t
WHERE jsonb_exists(t.worker_ids, :workerId)
ORDER BY t.created_at

10-05 18:37