Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA support for querying Postgres JSON fields

Tags:

Is there already support in JPA for dealing with queries on JSON fields like the following :

select * from person where (info ->> 'age')::numeric = 40;

select * from person where info ->> 'firstName'= 'Cabalo';

I'm using hibernate 5 (behind spring-data-jpa) and Postgres 9.4

like image 681
marius_neo Avatar asked Feb 04 '16 16:02

marius_neo


People also ask

Can you query JSON in Postgres?

Postgres is a relational database that allows you to combine relational and non-relational data effortlessly, giving users/applications flexibility in accessing and handling the data. Additionally, Postgres includes native support for querying and processing JSON data.

Is JSON supported in PostgreSQL?

PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.


1 Answers

JPA doesn't natively support converting JSON or JSONB fields. You will need to create an javax.persistence.AttributeConverter in order to to/from JSON/JSONB. Another important class to remember is org.postgresql.util.PGobject , which is useful for converting to/fromjsonb` fields.

Secondly, JPA is only an API. You will need to customize your underlying implementation in order to fully take advantage of this type. You will need to create org.hibernate.dialect.function.SQLFunction in order to use JSON/JSONB functions. You will need to register this along with your created AttributeConverter types in org.hibernate.dialect.PostgreSQL95Dialect.

Another note: it may be beneficial to refer to the json/jsonb operators you are using as native function calls or as an alias when creating SQLFunction. There is a tendency for native queries containing a ? operator to get mangled even when it is properly escaped.

See Hibernate Javadocs and JPA Javadocs.

like image 58
yodacola Avatar answered Oct 07 '22 17:10

yodacola