eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)