Persist a JSON object using Hibernate

Issue: BAEL-2353
This commit is contained in:
j-bennett 2018-12-10 18:27:48 -05:00 committed by Josh Cummings
parent e51a0d0428
commit 7ddcb76c09
5 changed files with 251 additions and 0 deletions

View File

@ -51,6 +51,11 @@
<artifactId>hibernate-testing</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
@ -69,6 +74,7 @@
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<h2database.version>1.4.196</h2database.version>
<assertj-core.version>3.8.0</assertj-core.version>
<jackson.version>2.8.11.3</jackson.version>
</properties>
</project>

View File

@ -0,0 +1,80 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@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;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCustomerAttributeJSON() {
return customerAttributeJSON;
}
public void setCustomerAttributeJSON(String customerAttributeJSON) {
this.customerAttributeJSON = customerAttributeJSON;
}
public Map<String, Object> getCustomerAttributes() {
return customerAttributes;
}
public void setCustomerAttributes(Map<String, Object> customerAttributes) {
this.customerAttributes = customerAttributes;
}
private static final ObjectMapper objectMapper = new ObjectMapper();
public void serializeCustomerAttributes() throws JsonProcessingException {
this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);
}
public void deserializeCustomerAttributes() throws IOException {
this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class);
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.AttributeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.hibernate.interceptors.CustomInterceptor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
private final ObjectMapper objectMapper = new ObjectMapper();
@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;
}
}

View File

@ -0,0 +1,111 @@
package com.baeldung.hibernate.persistjson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersistJSONUnitTest {
private Session session;
@Before
public void init() {
try {
Configuration configuration = new Configuration();
Properties properties = new Properties();
properties.load(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("hibernate-persistjson.properties"));
configuration.setProperties(properties);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Customer.class);
SessionFactory factory = metadataSources.buildMetadata()
.buildSessionFactory();
session = factory.openSession();
} catch (HibernateException | IOException e) {
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
}
}
@After
public void close() {
if (session != null)
session.close();
}
@Test
public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException {
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();
Map<String, Object> deserialized = customer.getCustomerAttributes();
assertEquals("123 Main Street", deserialized.get("address"));
}
@Test
public void givenCustomer_whenSaving_thenAttributesAreConverted() {
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);
session.beginTransaction();
int id = (int) session.save(customer);
session.flush();
session.clear();
Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(2, result.getCustomerAttributes()
.size());
}
}

View File

@ -0,0 +1,7 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop