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.

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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

In this tutorial, we’ll explore Spring R2DBC Migrations using Flyway, an open-source tool that’s commonly used for database migrations. Although it doesn’t have native support for R2DBC as of this writing, we’ll look at alternative ways to migrate tables and data during application start-up.

2. Basic Spring R2DBC Application

For this article, we’ll use a simple Spring R2DBC application with migrations using Flyway to create tables and insert data into a PostgreSQL database.

2.1. R2DBC

R2DBC stands for Reactive Relational Database. It’s based on the Reactive Streams specification, which provides a fully-reactive non-blocking API for interacting with SQL databases. However, despite its many benefits, some tools like Flyway don’t currently support R2DBC, which means that a JDBC (blocking) driver is required for migrations using Flyway.

Database migrations allow the application to upgrade the database schema on startup as new versions are deployed. These migrations are required to match the database structure to the application’s needs. Because these changes are required before the app can start, a synchronous blocking migration is acceptable.

2.2. Dependencies

We’ll need a few dependencies to make an R2DBC application compatible with Flyway.

We’ll need the spring-boot-starter-data-r2dbc dependency, which provides core Spring R2DBC data abstractions and the PostgreSQL R2DBC driver:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
  <groupId>org.postgresql</groupId>
   <artifactId>r2dbc-postgresql</artifactId>
   <version>1.0.5.RELEASE</version>
</dependency>

In order to configure database migrations, we’ll need Flyway:

<dependency>
  <groupId>org.flywaydb</groupId>
  <artifactId>flyway-core</artifactId>
  <version>10.12.0</version>
</dependency>

Since Flyway doesn’t yet support the R2DBC driver, we’ll need to add the standard JDBC driver for PostgreSQL as well:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.7.3</version>
</dependency>

3. Flyway Migration on the Spring R2DBC Application

Let’s look at the configuration required for Flyway migrations and sample scripts.

3.1. Configuration for Spring R2DBC and Flyway

Since Flyway does not work with R2DBC, we’ll need to create the Flyway bean with the init method migrate(), which prompts Spring to run our migrations as soon as it creates the bean:

@Configuration
@EnableConfigurationProperties({ R2dbcProperties.class, FlywayProperties.class })
class DatabaseConfig {
    @Bean(initMethod = "migrate")
    public Flyway flyway(FlywayProperties flywayProperties, R2dbcProperties r2dbcProperties) {
      return Flyway.configure()
        .dataSource(
            flywayProperties.getUrl(),
            r2dbcProperties.getUsername(),
            r2dbcProperties.getPassword()
        )
        .locations(flywayProperties.getLocations()
          .stream()
          .toArray(String[]::new))
        .baselineOnMigrate(true)
        .load();
    }
}

We can point Flyway to our database by merging the R2DBC properties with some overrides specific for Flyway, specifically the URL, which must be a JDBC connection URL and the locations Flyway will run migrations from.

In this particular example, Spring is able to auto-configure Postgresql R2DBC based on the dependency in the classpath, but it’s worth noting that R2DBC provides support for other SQL database drivers as well. Since we have the R2DBC starter in our application, we just need to set the appropriate properties for Spring R2DBC, but no additional config is needed.

Let’s see an example of a property file for the R2DBC PostgreSQL and Flyway setup that contains the database URL required for the JDBC driver:

spring:
  r2dbc:
    username: local
    password: local
    url: r2dbc:postgresql://localhost:8082/flyway-test-db
  flyway:
    url: jdbc:postgresql://localhost:8082/flyway-test-db
    locations: classpath:db/postgres/migration

While the default location of the directory is db/migration, the above configuration specifies that our migration scripts are located in the db/postgres/migration directory.

The R2DBC URL format consists of:

  • jdbc/r2dbc – Connection strategy
  • postgresql – Database type
  • localhost:8082 – Host of the PostgreSQL DB
  • flyway-test-db – Database name

3.2. Migration Scripts

Let’s create migration scripts that create two tables – department and student – and also insert some data into the department table.

Our first script will create the department and student tables. We’ll name it V1_1__create_tables.sql, adhering to the file naming convention so that Flyway can identify it as the first script to execute. Flyway tracks all the scripts that it has run, so it will only run each script once:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS department
(
    ID uuid PRIMARY KEY UNIQUE DEFAULT uuid_generate_v4(),
    NAME varchar(255)
);

CREATE TABLE IF NOT EXISTS student
(
    ID uuid PRIMARY KEY UNIQUE DEFAULT uuid_generate_v4(),
    FIRST_NAME varchar(255),
    LAST_NAME varchar(255),
    DATE_OF_BIRTH DATE NOT NULL,
    DEPARTMENT uuid NOT NULL CONSTRAINT student_foreign_key1 REFERENCES department (ID)
);

Our next script will insert some data into our tables. We’ll name it V1_2__insert_department.sql so that it runs second:

insert into department(NAME) values ('Computer Science');
insert into department(NAME) values ('Biomedical');

3.3. Testing Spring R2DBC Migrations

Let’s do a quick test to validate the setup.

First, let’s write a sample docker-compose.yml for starting PostgreSQL DB:

version: '3.9'
networks:
  obref:
services:
  postgres_db_service:
    container_name: postgres_db_service
    image: postgres:11
    ports:
      - "8082:5432"
    hostname:   postgres_db_service
    environment:
      - POSTGRES_PASSWORD=local
      - POSTGRES_USER=local
      - POSTGRES_DB=flyway-test-db

The first time we start the application, we should see logs confirming the migrations being applied:

INFO 95740 --- [  restartedMain] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 9.14.1 by Redgate
INFO 95740 --- [  restartedMain] o.f.c.internal.license.VersionPrinter    : See what's new here: https://flywaydb.org/documentation/learnmore/releaseNotes#9.14.1
INFO 95740 --- [  restartedMain] o.f.c.internal.license.VersionPrinter    : 
INFO 95740 --- [  restartedMain] o.f.c.i.database.base.BaseDatabaseType   : Database: jdbc:postgresql://localhost:8082/flyway-test-db (PostgreSQL 11.16)
INFO 95740 --- [  restartedMain] o.f.core.internal.command.DbValidate     : Successfully validated 2 migrations (execution time 00:00.007s)
INFO 95740 --- [  restartedMain] o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table "public"."flyway_schema_history" ...
INFO 95740 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Current version of schema "public": << Empty Schema >>
INFO 95740 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Migrating schema "public" to version "1.1 - create tables"
INFO 95740 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Migrating schema "public" to version "1.2 - insert department"
INFO 95740 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Successfully applied 2 migrations to schema "public", now at version v1.2 (execution time 00:00.045s)
INFO 95740 --- [  restartedMain] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 8080
INFO 95740 --- [  restartedMain] c.b.e.r.f.SpringWebfluxFlywayApplication : Started SpringWebfluxFlywayApplication in 1.895 seconds (JVM running for 2.28)

We can see from the above logs that the migration scripts are applied in the expected order.

If the flyway_schema_history table is not available, then Flyway creates it and stores the details of the migration status. Once the script completes, we can view details about the migrations from this table, including the name of the file and the time of execution.

4. Conclusion

In this article, we created a basic Spring R2DBC application and explored one of the ways to migrate data using Flyway for an application using R2DBC. We also employed some strategies to verify that Flyway applied our migrations as we expected.

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)
5 Comments
Oldest
Newest
Inline Feedbacks
View all comments