Storing untyped objects with Spring data and MySQL Json Data Type

Bassem 01/01

Sometimes we face a requirement where we have to save an unstructured data into our database, in this case we face two issues. The first one is the database if you are using a no-sql database, we are on the safe side, if not we have to see if the sql database used support json type columns or not.
The second issue is the language and the framework, in Java specifically hibernate does not support json type natively.
In this article we are going to create a demo using mysql 5.7, spring data 3.0.0 and hypersistence-utils library. This last one will help us in mapping JSON column to a JPA entity.

Code example

First we creat our table:

  `body` varchar(255) DEFAULT NULL,
  `comment` json DEFAULT NULL,
  PRIMARY KEY (`id`)

In this demo i am using flywaydb, the above-mentioned script will be placed under src/main/resources/db/migration, this will help us with initializing of the table and any future modification for the database.

In our pom.xml, we just need to add the following hypersistence-utils library, in order to map correctly the Json fields.


Next, we create our entity class Post which will represent a blog post as follow:

public class Post {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String body;

    private JsonNode comment;

    // skip getters and setters

And as you see for the comment object we are using JsonNode from com.fasterxml.jackson to map the json column.

Now we take a look at our repository:

public interface PostRepository extends JpaRepository<Post, Long> {
    @Query(value = """
                SELECT * FROM post 
                comment->"$.key" = :comment
            """, nativeQuery = true)
    Optional<Post> getPostByCommentKey(String comment); 

Here we use a native query to explore the MySQL Json feature. We defined a method to get a post, which will contain a comment, that have a name key with a value equal to the string param comment.

Next we create our representation layer:

public class PostController {
    // skip constructor

    public Postdto createPost(@RequestBody Postdto postToCreate) {
        var post = new Post();
        return new Postdto(post.getBody(), post.getComment());

    public Postdto getPostByComment(@PathVariable String body) {
        var found = postRepo.getPostByCommentKey(body).orElseThrow();
        return new Postdto(found.getBody(), found.getComment());

We have two endpoints, one to create the post and other one to get the post based on the comment.

Finally, we can demo our code by the following integration test:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = {JsonHibernateApplication.class, TestContainerConfig.class})
class JsonHibernateApplicationTests {
  // skip local vars

    void whenCreatPostThenSuccess() {
        var postBody = "bodyPost";
        var commentBody = "commentPost";
        var req = new Postdto(postBody, mapper.createObjectNode().put("key", commentBody));
        Postdto actual = restTemplate.postForObject(BASE , req, Postdto.class);
        assertFalse(actual.comment().get("key").isMissingNode());"comment body: " + actual.comment().toString());
        assertEquals(commentBody, actual.comment().path("key").asText());

    void whenGetPostByCommentThenSuccess() {
        Postdto actual = restTemplate.getForObject(BASE + "/comments/{body}", Postdto.class, "bodyComment222");
        assertFalse(actual.comment().get("key").isMissingNode());"comment body: " + actual.comment().toString());
        assertEquals("bodyComment222", actual.comment().path("key").asText());


In @SpringBootTest annotation we define the configuration for our test. To be highlighted we are using Testcontainers with a MySQL server, the related configuration can be found in the TestContainerConfig.class.
For each test we are executing the sql script init-db.sql:

INSERT INTO post (id, body, comment)
(1, 'post1', '{"key":"bodyComment"}'),
(2, 'post2', '{"key":"bodyComment222"}');

Basically we clear our database and insert new posts.

Now running the test we can see how the Json object comment is logged correctly:

2023-01-01T12:13:19.412+04:00  INFO 731173 --- [           main] d.s.j.JsonHibernateApplicationTests      : comment body: {"key":"commentPost"}
2023-01-01T12:13:19.467+04:00  INFO 731173 --- [           main] d.s.j.JsonHibernateApplicationTests      : comment body: {"key":"bodyComment222"}

That's it; all the code written in this article can be found on GitHub.

Feel free to join the conversation on Twitter 👇