Last updated: 2024-04-15
Working with JSON type in Hibernate and Spring Boot
With Hibernate 6, it is now possible to assign the type SqlTypes.JSON
directly to individual columns. How does this work and what do we need to be aware of?
Previously, we had to use the hypersistence-utils library for JSON fields. This is no longer required. The new Hibernate type works wonderfully for the persistence of custom types as well as Map
and List
types.
Let's assume we want to extend our microservice example and add a PartDetails
field to the CarPart
table. The JSON should have the following structure.
Example JSON we want to add to the car_part table
For this we first need the model classes representing our JSON. They're containing some validation constraints as well - that's optional but a good thing to ensure before persisting.
Our new model classes representing our JSON structure
In order for Hibernate to know wheater it needs to perform an update due to a change to the entity, all fields are compared with its original value. Therefore, our data objects must implement the equals()
method - in our example simply with the help of the Lombok annotation.
With this setup we can extend our CarPart
entity in the following way.
CarPart class with the new JSON field
The Hibernate type code SqlTypes.JSON
will handle all the conversions for us transparently in the background. The value for columnDefinition
must be "json"
for our MySql database.
By default Hibernate will create an instance of ObjectMapper
from the classpath. However, if we're running a Spring Boot app, we can directly reuse the configured ObjectMapper
from the application context.
Providing a HibernatePropertiesCustomizer through our config
We can now already work with the model classes in our code! If the partDetails
field at the CarPart
entity is not null, it is persisted as JSON in our database.
A new Spring Boot app with any custom database schema including JSON types can be created in the Free plan of Bootify. This provides the complete setup described above - all JPA entities with their annotations, the required configuration as well as the model classes with the required equals()
implementation.