gpt4 book ai didi

jpa - 如何将 PSQLs::json @>::json 转换为 jpa/jpql 谓词

转载 作者:行者123 更新时间:2023-12-04 02:49:30 25 4
gpt4 key购买 nike

假设我有一个看起来像这样的数据库表:

CREATE TABLE myTable(
id BIGINT,
date TIMESTAMP,
user_ids JSONB
);
user_idsJSONB-ARRAY
让这个表的记录看起来像这样:
{
"id":13,
"date":"2019-01-25 11:03:57",
"user_ids":[25, 661, 88]
};

我需要查询 user_ids 包含 25 的所有记录。在 SQL 中,我可以使用以下选择语句来实现它:
SELECT * FROM myTable where user_ids::jsonb @> '[25]'::jsonb;

现在我需要编写一个 JPA-Predicate 来呈现 "user_ids::jsonb @> '[25]'::jsonb"到休眠可解析/可执行标准,然后我打算在 session.createQuery() 中使用它陈述。
简单来说,我需要知道如何编写该 PSQL 片段 (user_ids::jsonb @> '[25]'::jsonb)作为 HQL 表达式。

最佳答案

幸运的是,PostgreSQL 中的每个比较运算符都只是一个函数的别名,您可以通过 psql 找到别名。控制台输入 \doS+和运算符(尽管某些运算符在此搜索中被视为通配符,因此它们提供的结果比预期的要多)。

结果如下:

postgres=# \doS+ @>
List of operators
Schema | Name | Left arg type | Right arg type | Result type | Function | Description
------------+------+---------------+----------------+-------------+---------------------+-------------
pg_catalog | @> | aclitem[] | aclitem | boolean | aclcontains | contains
pg_catalog | @> | anyarray | anyarray | boolean | arraycontains | contains
pg_catalog | @> | anyrange | anyelement | boolean | range_contains_elem | contains
pg_catalog | @> | anyrange | anyrange | boolean | range_contains | contains
pg_catalog | @> | box | box | boolean | box_contain | contains
pg_catalog | @> | box | point | boolean | box_contain_pt | contains
pg_catalog | @> | circle | circle | boolean | circle_contain | contains
pg_catalog | @> | circle | point | boolean | circle_contain_pt | contains
pg_catalog | @> | jsonb | jsonb | boolean | jsonb_contains | contains
pg_catalog | @> | path | point | boolean | path_contain_pt | contains
pg_catalog | @> | polygon | point | boolean | poly_contain_pt | contains
pg_catalog | @> | polygon | polygon | boolean | poly_contain | contains
pg_catalog | @> | tsquery | tsquery | boolean | tsq_mcontains | contains
(13 rows)

你想要的是两边的 jsonb 参数,我们看到了名为 jsonb_contains 的函数。 .所以相当于 jsonbcolumn @> jsonbvaluejsonb_contains(jsonbcolumn, jsonbvalue) .现在您不能在 JPQL 或 CriteriaBuilder 中使用该函数,除非您在使用 Hibernate 时通过自定义方言注册它。如果您使用 EclipseLink,我不知道那里的情况。

从这里开始,您的选择是使用 native 查询,或通过扩展现有方言来添加您自己的 Hibernate 方言。

关于jpa - 如何将 PSQLs::json @>::json 转换为 jpa/jpql 谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com