Originally posted 5/28/16 by Judy Hsu Romano on her blog. Formatting of code styles much easier to read on original post!
I'm using spring boot with JPA and a MySQL backend database with several JSON columns. The following is the JSON converter class used to save and retrieve data to the JSON column. This article helped a lot.
This worked with:
Oracle Java 1.8.0_66
Spring Boot 1.3.1.RELEASE
1. Create a POJO to represent the JSON object that will be saved to the column.
2. Create a Converter Class that implements AttributerConverter.
3. The JPA Entity class that contains the JSON column needs to have the @Convert annotation for the documents column.
NOTE: You could also have in the JpaJsonDocumentsConverter class added the autoapply attribute to the @Converter annotation and set that to true to have JPA apply this converter to all entity attributes of type List<JsonDocuments>.
4. Verified with an integration test on the Spring Data JPA Repository class that uses this entity that these methods worked.
I did notice that the documents column could not be null, so when you create the new TableWithDocuments record, the documents column had to be set as an empty JsonArray if there were no documents. Adding in null checks in the JpaJsonDocumentsConverter convertToDatabaseColumn and convertToEntityAttribute did not help, it was inside the JPA code that would error out.
About our blog:
This blog (like Flock) was formed to amplify the voices of underrepresented technologists and help all of us fly higher together.