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:
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.0.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.9.8</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:
public void deserializeCustomerAttributes() throws IOException { this.customerAttributes = objectMapper.readValue(customerAttributeJSON, HashMap.class); }
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, Map.class); } 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.