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

INe*_*elp 3 jpa hql predicate jpql

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

CREATE TABLE myTable(
   id BIGINT, 
   date TIMESTAMP, 
   user_ids JSONB 
);
Run Code Online (Sandbox Code Playgroud)

user_ids 区域 JSONB-ARRAY

让这个表的记录看起来像这样:

{
     "id":13,
     "date":"2019-01-25 11:03:57",
     "user_ids":[25, 661, 88]
};
Run Code Online (Sandbox Code Playgroud)

我需要查询 user_ids 包含 25 的所有记录。在 SQL 中,我可以使用以下选择语句来实现它:

SELECT * FROM myTable where user_ids::jsonb @> '[25]'::jsonb;
Run Code Online (Sandbox Code Playgroud)

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

col*_*ict 5

幸运的是,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)
Run Code Online (Sandbox Code Playgroud)

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

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