Skip to content

Commit 7ddcb76

Browse files
j-bennettjzheaux
authored andcommitted
Persist a JSON object using Hibernate
Issue: BAEL-2353
1 parent e51a0d0 commit 7ddcb76

File tree

5 files changed

+251
-0
lines changed

5 files changed

+251
-0
lines changed

persistence-modules/hibernate5/pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@
5151
<artifactId>hibernate-testing</artifactId>
5252
<version>5.2.2.Final</version>
5353
</dependency>
54+
<dependency>
55+
<groupId>com.fasterxml.jackson.core</groupId>
56+
<artifactId>jackson-databind</artifactId>
57+
<version>${jackson.version}</version>
58+
</dependency>
5459
</dependencies>
5560

5661
<build>
@@ -69,6 +74,7 @@
6974
<mariaDB4j.version>2.2.3</mariaDB4j.version>
7075
<h2database.version>1.4.196</h2database.version>
7176
<assertj-core.version>3.8.0</assertj-core.version>
77+
<jackson.version>2.8.11.3</jackson.version>
7278
</properties>
7379

7480
</project>
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.baeldung.hibernate.persistjson;
2+
3+
import java.io.IOException;
4+
import java.util.Map;
5+
6+
import javax.persistence.Convert;
7+
import javax.persistence.Entity;
8+
import javax.persistence.Id;
9+
import javax.persistence.Table;
10+
11+
import com.fasterxml.jackson.core.JsonProcessingException;
12+
import com.fasterxml.jackson.databind.ObjectMapper;
13+
14+
@Entity
15+
@Table(name = "Customers")
16+
public class Customer {
17+
18+
@Id
19+
private int id;
20+
21+
private String firstName;
22+
23+
private String lastName;
24+
25+
private String customerAttributeJSON;
26+
27+
@Convert(converter = HashMapConverter.class)
28+
private Map<String, Object> customerAttributes;
29+
30+
public int getId() {
31+
return id;
32+
}
33+
34+
public void setId(int id) {
35+
this.id = id;
36+
}
37+
38+
public String getFirstName() {
39+
return firstName;
40+
}
41+
42+
public void setFirstName(String firstName) {
43+
this.firstName = firstName;
44+
}
45+
46+
public String getLastName() {
47+
return lastName;
48+
}
49+
50+
public void setLastName(String lastName) {
51+
this.lastName = lastName;
52+
}
53+
54+
public String getCustomerAttributeJSON() {
55+
return customerAttributeJSON;
56+
}
57+
58+
public void setCustomerAttributeJSON(String customerAttributeJSON) {
59+
this.customerAttributeJSON = customerAttributeJSON;
60+
}
61+
62+
public Map<String, Object> getCustomerAttributes() {
63+
return customerAttributes;
64+
}
65+
66+
public void setCustomerAttributes(Map<String, Object> customerAttributes) {
67+
this.customerAttributes = customerAttributes;
68+
}
69+
70+
private static final ObjectMapper objectMapper = new ObjectMapper();
71+
72+
public void serializeCustomerAttributes() throws JsonProcessingException {
73+
this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);
74+
}
75+
76+
public void deserializeCustomerAttributes() throws IOException {
77+
this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class);
78+
}
79+
80+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.baeldung.hibernate.persistjson;
2+
3+
import java.io.IOException;
4+
import java.util.Map;
5+
6+
import javax.persistence.AttributeConverter;
7+
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
import com.baeldung.hibernate.interceptors.CustomInterceptor;
12+
import com.fasterxml.jackson.core.JsonProcessingException;
13+
import com.fasterxml.jackson.databind.ObjectMapper;
14+
15+
public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {
16+
17+
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
18+
19+
private final ObjectMapper objectMapper = new ObjectMapper();
20+
21+
@Override
22+
public String convertToDatabaseColumn(Map<String, Object> customerInfo) {
23+
24+
String customerInfoJson = null;
25+
try {
26+
customerInfoJson = objectMapper.writeValueAsString(customerInfo);
27+
} catch (final JsonProcessingException e) {
28+
logger.error("JSON writing error", e);
29+
}
30+
31+
return customerInfoJson;
32+
}
33+
34+
@Override
35+
public Map<String, Object> convertToEntityAttribute(String customerInfoJSON) {
36+
37+
Map<String, Object> customerInfo = null;
38+
try {
39+
customerInfo = objectMapper.readValue(customerInfoJSON, Map.class);
40+
} catch (final IOException e) {
41+
logger.error("JSON reading error", e);
42+
}
43+
44+
return customerInfo;
45+
}
46+
47+
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
package com.baeldung.hibernate.persistjson;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.fail;
5+
6+
import java.io.IOException;
7+
import java.util.HashMap;
8+
import java.util.Map;
9+
import java.util.Properties;
10+
11+
import org.hibernate.HibernateException;
12+
import org.hibernate.Session;
13+
import org.hibernate.SessionFactory;
14+
import org.hibernate.boot.MetadataSources;
15+
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
16+
import org.hibernate.cfg.Configuration;
17+
import org.hibernate.service.ServiceRegistry;
18+
import org.junit.After;
19+
import org.junit.Before;
20+
import org.junit.Test;
21+
22+
public class PersistJSONUnitTest {
23+
24+
private Session session;
25+
26+
@Before
27+
public void init() {
28+
try {
29+
Configuration configuration = new Configuration();
30+
31+
Properties properties = new Properties();
32+
properties.load(Thread.currentThread()
33+
.getContextClassLoader()
34+
.getResourceAsStream("hibernate-persistjson.properties"));
35+
36+
configuration.setProperties(properties);
37+
38+
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
39+
.build();
40+
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
41+
metadataSources.addAnnotatedClass(Customer.class);
42+
43+
SessionFactory factory = metadataSources.buildMetadata()
44+
.buildSessionFactory();
45+
46+
session = factory.openSession();
47+
} catch (HibernateException | IOException e) {
48+
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
49+
}
50+
}
51+
52+
@After
53+
public void close() {
54+
if (session != null)
55+
session.close();
56+
}
57+
58+
@Test
59+
public void givenCustomer_whenCallingSerializeCustomerAttributes_thenAttributesAreConverted() throws IOException {
60+
61+
Customer customer = new Customer();
62+
customer.setFirstName("first name");
63+
customer.setLastName("last name");
64+
65+
Map<String, Object> attributes = new HashMap<>();
66+
attributes.put("address", "123 Main Street");
67+
attributes.put("zipcode", 12345);
68+
69+
customer.setCustomerAttributes(attributes);
70+
71+
customer.serializeCustomerAttributes();
72+
73+
String serialized = customer.getCustomerAttributeJSON();
74+
75+
customer.setCustomerAttributeJSON(serialized);
76+
customer.deserializeCustomerAttributes();
77+
78+
Map<String, Object> deserialized = customer.getCustomerAttributes();
79+
80+
assertEquals("123 Main Street", deserialized.get("address"));
81+
}
82+
83+
@Test
84+
public void givenCustomer_whenSaving_thenAttributesAreConverted() {
85+
86+
Customer customer = new Customer();
87+
customer.setFirstName("first name");
88+
customer.setLastName("last name");
89+
90+
Map<String, Object> attributes = new HashMap<>();
91+
attributes.put("address", "123 Main Street");
92+
attributes.put("zipcode", 12345);
93+
94+
customer.setCustomerAttributes(attributes);
95+
96+
session.beginTransaction();
97+
98+
int id = (int) session.save(customer);
99+
100+
session.flush();
101+
session.clear();
102+
103+
Customer result = session.createNativeQuery("select * from Customers where Customers.id = :id", Customer.class)
104+
.setParameter("id", id)
105+
.getSingleResult();
106+
107+
assertEquals(2, result.getCustomerAttributes()
108+
.size());
109+
}
110+
111+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
hibernate.connection.driver_class=org.h2.Driver
2+
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
3+
hibernate.connection.username=sa
4+
hibernate.dialect=org.hibernate.dialect.H2Dialect
5+
6+
hibernate.show_sql=true
7+
hibernate.hbm2ddl.auto=create-drop

0 commit comments

Comments
 (0)