jpa 标准 api 中 PostgreSQL 函数“jsonb_path_exists”的用法

Geo*_*ser 1 postgresql jpa criteria-api

我想使用 JPA 标准 api 调用 postgresql 函数jsonb_path_existshttps://www.postgresql.org/docs/12/functions-json.html)。

假设我有以下查询:

select id from person where jsonb_path_exists(person.json,'$.some_property[0].typ ? (@ =="Something")');
Run Code Online (Sandbox Code Playgroud)

通过 CriteriaBuilder 我会做类似的事情:

        var jsonQuery = jsonPath + " ? (@ ==\"" + value + "\")"; // evaluates to '$.some_property[0].typ ? (@ =="Something")'
        criteriaBuilder.function("jsonb_path_exists",
                        String.class,
                        entityRoot.get("json"),
                        criteriaBuilder.literal(jsonQuery)
                )
                .in(Boolean.TRUE);
Run Code Online (Sandbox Code Playgroud)

但是我还没有弄清楚如何将作为字符串提供的 jsonQuery 转换为 postgresjsonpath类型。因此我收到以下异常:

org.postgresql.util.PSQLException: ERROR: function jsonb_path_exists(jsonb, character varying) does not exist
Run Code Online (Sandbox Code Playgroud)

正确的签名是 jsonb_path_exists(target jsonb, path jsonpath [, vars jsonb [, silent bool]])

所有带有jsonpath参数的函数都存在此问题,例如jsonb_path_query, jsonb_path_match,jsonb_path_query_first

有人知道如何解决这个问题吗?

Geo*_*ser 5

我通过编写一个 PostgreSQL 包装函数解决了这个问题,我现在调用它而不是jsonb_path_exists

CREATE OR REPLACE FUNCTION jsonb_filter(target jsonb, path varchar)
  RETURNS boolean
  LANGUAGE plpgsql IMMUTABLE STRICT cost 1 AS
$func$
  BEGIN
      RETURN jsonb_path_exists(target,CAST(path AS jsonpath));
  END
$func$;
Run Code Online (Sandbox Code Playgroud)

调用创建的jsonb_filter函数可以完成以下工作:

        return criteriaBuilder.function("jsonb_filter",
                String.class,
                entityRoot.get("json"),
                jsonPathExpression
        ).in(Boolean.TRUE);
Run Code Online (Sandbox Code Playgroud)

确保不要在 中包含单引号jsonPathExpression,例如 use$.your_expression代替'$.your_expression'