Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

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