Hibernate does not support JSON natively, so you need to use something like the hibernate-types if you want to persist and fetch JSON properties using Hibernate.
In your example, the problem is that you need to map the Types.OTHER
JDBC type to JsonNodeBinaryType
Hibernate Type offered by the hibernate-types which can be done as follows.
At the Dialect
level
public class PostgreSQL95JsonDialect
extends PostgreSQL95Dialect {
public PostgreSQL95JsonDialect() {
super();
this.registerHibernateType(
Types.OTHER, JsonNodeBinaryType.class.getName()
);
}
}
And provide the new Dialect to Hibernate:
<property
name="hibernate.dialect"
value="com.vladmihalcea.book.hpjp.hibernate.type.json.PostgreSQL95JsonDialect"
/>
At the Query level
By using the addScalar
Hibernate-specific method:
JsonNode properties = (JsonNode) entityManager
.createNativeQuery(
"SELECT properties " +
"FROM book " +
"WHERE isbn = :isbn")
.setParameter("isbn", "978-9730228236")
.unwrap(org.hibernate.query.NativeQuery.class)
.addScalar("properties", JsonNodeBinaryType.INSTANCE)
.getSingleResult();
For more details, check out this article.