【问题标题】:How to query in jsonb postgresql and convert to predicate JPA如何在 jsonb postgresql 中查询并转换为谓词 JPA
【发布时间】:2020-07-02 21:45:08
【问题描述】:

我卡住了:)

有谁知道如何在 jsonb 中查询 postgresql 我有表 USER

  • INT ID,
  • Varchar 名称,
  • jsonb categoryId

categoryId 字段中的示例数据如下 = [1,2,3,4,5]

我已经尝试过这个有效的查询:

select * 
from user where categoryId @> '2'::jsonb ;  

但是如何使用多个参数进行查询,例如

select * 
from user 
where categoryId @> '1,3,4'::jsonb

我将实现这个来休眠 jpa/jpql-predicate,但我想先了解本地查询

非常感谢

【问题讨论】:

    标签: java postgresql hibernate jpa jsonb


    【解决方案1】:

    在 SQL 中,您可以为此使用 ?| operator

    select *
    from "user"
    where categoryid ?| array['1','3','4'];
    

    这将返回 JSON 数组中至少包含一个值的行。如果要查找包含 all 值的值,请改用 ?& 运算符。


    要使用 @> 运算符,您需要在右侧使用 JSON 数组:

    select *
    from "user"
    where categoryid @> '[1,3,4]'::jsonb
    

    请注意,user 是保留关键字。每次要引用该表时,都必须将其括在双引号中。我强烈建议找到一个不同的表名。

    【讨论】:

    • 有效!非常感谢,以及如何在 JPA 中转换为标准构建器,我尝试使用标准构建器.function,但我仍然无法使用,我尝试这样,但错误:predicates.add(criteriaBuilder.and(criteriaBuilder.function("jsonb_contains ", Integer.class, expPreferedCountry, expPreferedCountry )));
    • @herure279:抱歉,不知道。我不使用 JPA
    猜你喜欢
    • 2021-01-24
    • 2014-08-04
    • 1970-01-01
    • 2016-03-25
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2018-03-07
    相关资源
    最近更新 更多