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

Mapping data collections in an SQL table field is a common approach when we want to store non-relational data within our entity. In Hibernate 6, there are changes to the default mapping mechanisms that make storing such data more efficient on the database side.

In this article, we’ll review those changes. Additionally, we’ll discuss possible approaches to migrating data persisted using Hibernate 5.

2. New Basic Array/Collection Mapping in Hibernate 6.x

Before Hibernate 6, we had unconditional mapping for collections where the type code SqlTypes.VARBINARY was used by default. Under the hood, we serialized the contents with Java serialization. Now, due to changes in the mapping, we can map collections as native array implementations, JSON, or XML.

Let’s review a few popular SQL dialects and see how they map collection-type fields. First, al of all, let’s add the latest Spring Data JPA dependency which already contains a Hibernate 6.x under the hood:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Also, let’s add the H2 database dependency since we’ll be able to switch dialects and modes and check different databases’ behavior using it:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
</dependency>

Now let’s create the entity we’ll use in all the cases:

public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    Long id;
    List<String> tags;

    //getters and setters
}

We’ve created a User entity with the id and a list of user tags.

2.1. PostgreSQL Dialect

In the PostgreSQLDialect we have a supportsStandardArrays() method overridden and this driver supports a native array implementation for collections.

To review this behavior, let’s configure our database:

spring:
  datasource:
    url: jdbc:h2:mem:mydb;MODE=PostgreSQL
    username: sa
    password: password
    driverClassName: org.h2.Driver
  jpa:
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    show-sql: true    

We’ve configured H2 in PostgreSQL mode.  Also, we’ve specified a PostgreSQLDialect class as a database platform. We’ve enabled SQL script logging to see the type definitions for the table columns.

Now let’s get a mapping for our User entity and check the SQL type of the tags field:

static int ARRAY_TYPE_CODE = 2003;

@PersistenceContext
EntityManager entityManager;

@Test
void givenPostgresDialect_whenGetUserEntityFieldsTypes_thenExpectedTypeShouldBePresent() {
    MappingMetamodelImpl mapping = (MappingMetamodelImpl) entityManager.getMetamodel();

    EntityMappingType entityMappingType = mapping
      .getEntityDescriptor(User.class.getName())
      .getEntityMappingType();

    entityMappingType.getAttributeMappings()
      .forEach(attributeMapping -> {
          if (attributeMapping.getAttributeName().equals("tags")) {
              JdbcType jdbcType = attributeMapping.getSingleJdbcMapping().getJdbcType();
              assertEquals(ARRAY_TYPE_CODE, jdbcType.getJdbcTypeCode());
          }
      });
}

We’ve got the JDBC mapping and checked that the tags field has an array JDBC type code. Besides that, if we check the logs we’ll see that for this column the varchar array was chosen as an SQL type:

Hibernate: 
    create table users (
        id bigint not null,
        tags varchar(255) array,
        primary key (id)
    )

2.2. Oracle Dialect

In OracleDialect, we don’t have a supportsStandardArrays() method overridden. Despite this, inside the getPreferredSqlTypeCodeForArray() we have unconditional support for the array type for collections.

Let’s configure our database to test Oracle behavior:

spring:
  datasource:
    url: jdbc:h2:mem:mydb;MODE=Oracle
    username: sa
    password: password
    driverClassName: org.h2.Driver
  jpa:
    database-platform: org.hibernate.dialect.OracleDialect
    show-sql: true

We switched our database to the Oracle mode and specified the OracleDialect. Now, let’s run the type checking for our User entity:

@Test
void givenOracleDialect_whenGetUserEntityFieldsTypes_thenExpectedTypeShouldBePresent() {
    MappingMetamodelImpl mapping = (MappingMetamodelImpl) entityManager.getMetamodel();

    EntityMappingType entityMappingType = mapping
      .getEntityDescriptor(User.class.getName())
      .getEntityMappingType();

    entityMappingType.getAttributeMappings()
      .forEach(attributeMapping -> {
          if (attributeMapping.getAttributeName().equals("tags")) {
              JdbcType jdbcType = attributeMapping.getSingleJdbcMapping().getJdbcType();
              assertEquals(ARRAY_TYPE_CODE, jdbcType.getJdbcTypeCode());
          }
      });
}

As expected, we have an array JDBC type code in the tags field. Let’s take a look at what is shown in the logs:

Hibernate: 
    create table users (
        id number(19,0) not null,
        tags StringArray,
        primary key (id)
    )

As we can see, the StringArray SQL type is used for the tags column.

2.3. Custom Dialect

By default, there are no dialects for mapping collections as JSON or XML. Let’s create a custom dialect that uses JSON as a default type for collections typed fields:

public class CustomDialect extends Dialect {

    @Override
    public int getPreferredSqlTypeCodeForArray() {
        return supportsStandardArrays() ? ARRAY : JSON;
    }

    @Override
    protected void registerColumnTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
        super.registerColumnTypes( typeContributions, serviceRegistry );
        final DdlTypeRegistry ddlTypeRegistry = 
        typeContributions.getTypeConfiguration().getDdlTypeRegistry();
        ddlTypeRegistry.addDescriptor( new DdlTypeImpl( JSON, "jsonb", this ) );
    }
}

We’ve registered support for the JSON type and added it as a default type for collections mapping. Now let’s configure our database:

spring:
  datasource:
    url: jdbc:h2:mem:mydb;MODE=PostgreSQL
    username: sa
    password: password
    driverClassName: org.h2.Driver
  jpa:
    database-platform: com.baeldung.arrayscollections.dialects.CustomDialect

We’ve switched our database to the PostgreSQL mode since it supports a jsonb type. Also, we started using our CustomDialect class.

Now we’ll check the type mapping again:

static int JSON_TYPE_CODE = 3001;

@Test
void givenCustomDialect_whenGetUserEntityFieldsTypes_thenExpectedTypeShouldBePresent() {
    MappingMetamodelImpl mapping = (MappingMetamodelImpl) entityManager.getMetamodel();

    EntityMappingType entityMappingType = mapping
      .getEntityDescriptor(User.class.getName())
      .getEntityMappingType();

    entityMappingType.getAttributeMappings()
      .forEach(attributeMapping -> {
          if (attributeMapping.getAttributeName().equals("tags")) {
              JdbcType jdbcType = attributeMapping.getSingleJdbcMapping().getJdbcType();
              assertEquals(JSON_TYPE_CODE, jdbcType.getJdbcTypeCode());
          }
      });
}

We can see the tags field was mapped as a JSON type.  Let’s check the logs:

Hibernate: 
    create table users (
        id bigint not null,
        tags jsonb,
        primary key (id)
    )

As expected, the jsonb column type was used for tags.

3. Migration From Hibernate 5.x to Hibernate 6.x

Different default types are used for collection mappings in Hibernate 5.x and Hibernate 6.x. To migrate to native array or JSON/XML types, we have to read our existing data through the Java serialization mechanism. Then, we need to write it back through the respective JDBC method for the type.

To demonstrate it, let’s create the entity that is expected to be migrated:

@Entity
@Table(name = "migrating_users")
public class MigratingUser {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @JdbcTypeCode(SqlTypes.VARBINARY)
    private List<String> tags;

    private List<String> newTags;

   // getters, setters
}

We created a newTags field, which is mapped as an array type by default, and explicitly used SqlTypes.VARBINARY for the existing tags field, as it’s the default mapping type in Hibernate version 5.x.

Now, let’s create a repository for our entity:

public interface MigratingUserRepository extends JpaRepository<MigratingUser, Long> {
}

Finally, let’s execute the migration logic:

@Autowired
MigratingUserRepository migratingUserRepository;

@Test
void givenMigratingUserRepository_whenMigrateTheUsers_thenAllTheUsersShouldBeSavedInDatabase() {
    prepareData();

    migratingUserRepository
      .findAll()
      .stream()
      .peek(u -> u.setNewTags(u.getTags()))
      .forEach(u -> migratingUserRepository.save(u));
}

We’ve read all the items from the database, copied their values to the new field, and saved them back into the database.  To control the memory consumption we can consider pagination during the reading process. To improve the persistence speed we can use the batching mechanism. After the migration, we can remove the old column from the table.

4. Conclusion

In this tutorial, we reviewed the new collections mapping in Hibernate 6.x. We explored how to use internal array types and JSON fields to store serialized collections. Additionally, we implemented a migration mechanism to the new database schema. With the new mapping, we no longer need to implement it ourselves to support a more efficient data type for our collections.

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)