How to query in jsonb postgresql and convert to predicate JPA

herure279 :

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

a_horse_with_no_name :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=348420&siteId=1