Persisting JSON with Spring Data

Basically every modern database system has its own data type to persist JSON. Using this type ensures at least the correct formatting, mostly there are also other advantages such as faster I/O.

As Spring Boot developers we want to access the JSON field without manually handling the mapping between the Java entity and the database. In the best case we work exclusively with the Java classes that represent the JSON; changes are mapped with Jackson and Hibernate transparently.

Creating the custom type in Bootify

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 car parts

To do this, we go to the tab "Data Objects" and first create the object "PartDetailsDimensions" with its three fields.

Adding the PartDetailsDimensions data object

Now we create the object "PartDetails". Since "PartDetailsDimensions" already exists, we can select it directly as a custom type.

Adding the PartDetails

Finally we add the new field "partDetails" with its corresponding type to the already existing "CarPart" entity.

Adding the new field to our entity

That's all! We can already download our source code, but let's have a closer look on the implementation as well.

Technical backgrounds

Spring Data / Hibernate does not support JSON fields out-of-the-box, but there is a library that provides custom types for the most common database systems: hibernate-types. This is a fantastic open source library, please support it!

In our example the CarPart class is now configured as follows:

New Annotations of our CarPart class

A custom type "json" is registered at the class, which becomes active for the annotated field. In our case (MySQL) the class JsonStringType takes over the transformation of PartDetails to JSON. Depending on the database a certain type is necessary, which is preselected by Bootify.

Reading and writing the partDetails now works like a charm without having to worry about any mappings.

Further readings

Map JSON objects with generic Hibernate types