Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

NPI – JPA Buddy – JPA (partner)
announcement - icon

JPA is huge! It covers nearly every aspect of communication between relational databases and the Java application and is deeply integrated into all major frameworks.

If you're using IntelliJ, JPA Buddy is super helpful. The plugin gently guides you through the subtleties of the most popular JPA implementations, visually reminds you of JPA features, generates code that follows best practices, and integrates intelligent inspections to improve your existing persistence code.

More concretely, it provides powerful tooling to generate Spring Data JPA repositories and methods, Flyway Versioned Migrations, Liquibase Differential Changelogs, DDL and SQL statements, DTO objects, and MapStruct interfaces.

Oh, and it actually generates JPA entities from an existing database and gradually update the data model as the database evolves! Yeah.

>> Become a lot more productive with JPA Buddy

Jackson Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

Some projects may require JSON objects to be persisted in a relational database.

In this tutorial, we’ll see how to take a JSON object and persist it in a relational database.

There are several frameworks available that provide this functionality, but we will look at a few simple, generic options using only Hibernate and Jackson.

2. Dependencies

We'll use the basic Hibernate Core dependency for this tutorial:


We’ll also be using Jackson as our JSON library:


Note that these techniques are not limited to these two libraries. We can substitute our favorite JPA provider and JSON library.

3. Serialize and Deserialize Methods

The most basic way to persist a JSON object in a relational database is to convert the object into a String before persisting it. Then, we convert it back into an object when we retrieve it from the database.

We can do this in a few different ways.

The first one we’ll look at is using custom serialize and deserialize methods.

We’ll start with a simple Customer entity that stores the customer’s first and last name, as well as some attributes about that customer.

A standard JSON object would represent those attributes as a HashMap, so that's what we'll use here:

@Table(name = "Customers")
public class Customer {

    private int id;

    private String firstName;

    private String lastName;

    private String customerAttributeJSON;

    @Convert(converter = HashMapConverter.class)
    private Map<String, Object> customerAttributes;

Rather than saving the attributes in a separate table, we are going to store them as JSON in a column in the Customers table. This can help reduce schema complexity and improve the performance of queries.

First, we’ll create a serialize method that will take our customerAttributes and convert it to a JSON string:

public void serializeCustomerAttributes() throws JsonProcessingException {
    this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);

We can call this method manually before persisting, or we can call it from the setCustomerAttributes method so that each time the attributes are updated, the JSON string is also updated.

Next, we’ll create a method to deserialize the JSON string back into a HashMap object when we retrieve the Customer from the database. We can do that by passing a TypeReference parameter to readValue():

public void deserializeCustomerAttributes() throws IOException {
    this.customerAttributes = objectMapper.readValue(customerAttributeJSON, 
    	new TypeReference<Map<String, Object>>() {});

Once again, there are a few different places that we can call this method from, but, in this example, we’ll call it manually.

So, persisting and retrieving our Customer object would look something like this:

public void whenStoringAJsonColumn_thenDeserializedVersionMatches() {
    Customer customer = new Customer();
    customer.setFirstName("first name");
    customer.setLastName("last name");

    Map<String, Object> attributes = new HashMap<>();
    attributes.put("address", "123 Main Street");
    attributes.put("zipcode", 12345);


    String serialized = customer.getCustomerAttributeJSON();


    assertEquals(attributes, customer.getCustomerAttributes());

4. Attribute Converter

If we are using JPA 2.1 or higher, we can make use of AttributeConverters to streamline this process.

First, we’ll create an implementation of AttributeConverter. We'll reuse our code from earlier:

public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {

    public String convertToDatabaseColumn(Map<String, Object> customerInfo) {

        String customerInfoJson = null;
        try {
            customerInfoJson = objectMapper.writeValueAsString(customerInfo);
        } catch (final JsonProcessingException e) {
            logger.error("JSON writing error", e);

        return customerInfoJson;

    public Map<String, Object> convertToEntityAttribute(String customerInfoJSON) {

        Map<String, Object> customerInfo = null;
        try {
            customerInfo = objectMapper.readValue(customerInfoJSON, 
            	new TypeReference<HashMap<String, Object>>() {});
        } catch (final IOException e) {
            logger.error("JSON reading error", e);

        return customerInfo;

Next, we tell Hibernate to use our new AttributeConverter for the customerAttributes field, and we're done:

@Convert(converter = HashMapConverter.class)
private Map<String, Object> customerAttributes;

With this approach, we no longer have to manually call the serialize and deserialize methods since Hibernate will take care of that for us. We can simply save and retrieve the Customer object normally.

5. Conclusion

In this article, we've seen several examples of how to persist JSON objects using Hibernate and Jackson.

Our first example looked at a simple, compatible method using custom serialize and deserialize methods. And second, we introduced AttributeConverters as a powerful way to simplify our code.

As always, make sure to check out the source code for this tutorial over on Github.

Persistence bottom

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

Jackson bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Persistence footer banner
Comments are closed on this article!