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 Hibernate, Jackson, and the Hypersistence Utils library.

2. Dependencies

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

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.4.24.Final</version>
</dependency>

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

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>

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:

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

    @Id
    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:

@Test
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);

    customer.setCustomerAttributes(attributes);
    customer.serializeCustomerAttributes();

    String serialized = customer.getCustomerAttributeJSON();

    customer.setCustomerAttributeJSON(serialized);
    customer.deserializeCustomerAttributes();

    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> {

    @Override
    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;
    }

    @Override
    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. Using the Hypersistence Utils Library

The Hypersistence library allows easy mapping of JSON to database systems like H2, MySQL, Oracle Database, etc. This is achieved by defining and using custom types in an entity class.

To use the library, we need to add the hypersistence-utils-hibernate-55 dependency to the pom.xml:

<dependency>
    <groupId>io.hypersistence</groupId>
    <artifactId>hypersistence-utils-hibernate-55</artifactId>
    <version>3.8.1</version>
</dependency>

This is compatible with Hibernate 5.5 and 5.6. For Hibernate 6.0 and 6.1, we need to use the hpersisitence-utils-hibernate-60 dependency instead. For Hibernate 6.2 and above, the hypersistence-utils-hibernate-62 dependency and the hypersistence-utils-hibernate-63 dependency are required respectively.

Next, let’s create an entity class named Warehouse:

@Entity
@TypeDef(name = "json", typeClass = JsonType.class)
public class Warehouse {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private String location;

    @Type(type = "json")
    @Column(columnDefinition = "json")
    private Map<String, String> attributes = new HashMap<>();
}

In the code above, we use the @TypeDef annotation to define a type name “json“, which is mapped to the JsonType.class from the Hypersistence Utils library. This mapping allows us to serialize and deserialize JSON in the database. We reference this type whenever we need to apply it as JSON.

Alternatively, we can specify the fully qualified name of the type in Hibernate 5:

@Type(type = "io.hypersistence.utils.hibernate.type.json.JsonType")
@Column(columnDefinition = "json")
private Map<String, String> attributes = new HashMap<>();

In this case, the @TypeDef annotation isn’t required because the custom type is explicitly defined.

However, starting with Hibernate 6, @TypeDef is deprecated. We can apply the custom type directly by specifying it within the @Type annotation:

@Type(JsonType.class)
private Map<String, String> attributes = new HashMap<>();

The JsonType.class is responsible for mapping JSON to the database.

6. The @JdbcTypeCode Annotation

Hibernate 6.0 and later versions provide an annotation named @JdbcTypeCode to help specify the JDBC type for column mapping.

We can serialize or deserialize a Map object as JSON by setting the SQL type to JSON using SQLTypes.JSON as the parameter of the @JdbcTypeCode annotation. This approach provides the flexibility to store structured data without the need for additional mapping configuration.

Let’s define an entity class named Store and map the attributes object as JSON:

@Entity
public class Store {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private String location;

    @JdbcTypeCode(SqlTypes.JSON)
    private Map<String, String> attributes = new HashMap<>();
}

In the code above, we define the SQL type of the attributes object by explicitly using @JdbcTypeCode annotation and setting the SQL type to JSON. This allows the attributes object to be serialized and deserialized as JSON without the need for an external library or writing a custom conversion.

7. Mapping JSON Document to an @Embeddable

Also, starting from Hibernate 6.0, we can map a JSON document to an embeddable class. A class with @Embeddable annotation can be included in another class as a value type and be persisted into the database as part of the containing class.

Furthermore, the @Embedded annotation is used in the containing class to indicate it contains an embedded object. To map an embedded class to a JSON object, we have to annotate it with @JdbcTypeCode annotation and set the annotation parameter to SQLTypes.JSON.

Notably, this feature is only available for Oracle DB and PostgreSQL as other databases are not supported yet.

Let’s define an embeddable class:

@Embeddable
public class Specification implements Serializable  {
    private int ram;
    private int internalMemory;
    private String processor;

    // standard constructor, getters and setters
}

Next, let’s embed the class into our entity class and map it as JSON:

@Entity
public class Phone {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Embedded
    @JdbcTypeCode(SqlTypes.JSON)
    private Specification specification;
}

In the code above, we annotate the Specification type with @Embedded to indicate it’s an embeddable class and we map the column to a JSON document by explicitly specifying the JDBC type code.

8. Conclusion

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

In the first example, we used a simple, compatible approach using custom serialize and deserialize methods. Then, in the second example, we introduced AttributeConverters as a powerful way to simplify our code. Also, we looked at a pre-defined type from the Hypersistence Utils library to simplify mapping JSON to a database column.

Finally, we saw how to use the @JdbcTypeCode annotation introduced in Hibernate 6 to simplify mapping JSON to a database column without custom configuration or using an external library.

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


« 上一篇: Spring 应用程序调试
» 下一篇: JVM代码缓存介绍