How to query in jsonb postgresql and convert to predicate JPA

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-11 14:47:56

问题


i have stuck :)

does anyone know how query postgresql in jsonb i have table USER

  • INT id,
  • Varchar name,
  • jsonb categoryId

the example data in categoryId field like this = [1,2,3,4,5]

I have tried this query which works:

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

but how to query with multiple params like

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

and i will implement this to hibernate jpa/jpql-predicate, but i want to know native query first

Thankyou so much


回答1:


In SQL you can use the ?| operator for this

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

That will return rows where at least one of the values is contained in the JSON array. If you want to find those that contain all values, use the ?& operator instead.


To use the @> operator you would need to use a JSON array on the right hand side:

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

Note that user is a reserved keyword. You will have to enclose it in double quotes every time you want to refer to the table. I would highly recommend to find a different table name.



来源:https://stackoverflow.com/questions/60796451/how-to-query-in-jsonb-postgresql-and-convert-to-predicate-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!