我想使用JPA调用postgresql函数jsonb_path_exists
(https://www.postgresql.org/docs/12/functions-json.html)。
假设我有以下查询:
select id from person where jsonb_path_exists(person.json,'$.some_property[0].typ ? (@ =="Something")');
通过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);
但是,我还没有弄清楚如何将jsonQuery作为字符串提供给postgres jsonpath
类型。因此,我收到以下例外情况:
org.postgresql.util.PSQLException: ERROR: function jsonb_path_exists(jsonb, character varying) does not exist
正确的签名是jsonb_path_exists(target jsonb, path jsonpath [, vars jsonb [, silent bool]])
对于所有具有jsonpath
参数的函数,例如jsonb_path_query
、jsonb_path_match
、jsonb_path_query_first
,都存在此问题
有人知道怎么解决这个问题吗?
发布于 2022-08-08 15:57:12
我已经通过编写一个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$;
调用创建的jsonb_filter
函数可以完成以下工作:
return criteriaBuilder.function("jsonb_filter",
String.class,
entityRoot.get("json"),
jsonPathExpression
).in(Boolean.TRUE);
确保在jsonPathExpression
中不要包含环绕单引号,例如使用$.your_expression
而不是'$.your_expression'
。
https://stackoverflow.com/questions/73223095
复制相似问题