Overview of Spring Data R2DBC

I introduced you to the Reactive Relational Database Connectivity (R2DBC) specs, about the Service Provider Interface library and the drivers that implement this SPI library in the previous tutorial. If your application uses Spring framework and wants to manipulate the database in a reactive mechanism, you can use Spring Data R2DBC to make manipulating the database more convenient and easier. How is it in detail? Let’s find out together in this tutorial!

First, I will create a new Maven project as an example:

I will use the PostgreSQL database as an example, so I will declare the PostgreSQL R2DBC driver and Spring Data R2DBC dependency as follows:

In the previous tutorial, I mentioned the object of the ConnectionFactory class to declare connection information to the database server, here is the PostgreSQL database. With Spring Data R2DBC, you also need to initialize the object of this ConnectionFactory class, as a bean in the Spring container.

Spring Data R2DBC provides us with an abstract class named AbstractR2dbcConfiguration to configure the beans needed for us to work with the database in a reactive manner.

In this AbstractR2dbcConfiguration class, you will see that it defines an abstract method to create a new object of the ConnectionFactory class. You need to create a new class that extends the AbstractR2dbcConfiguration class to define the bean for the ConnectionFactory class! My example is as follows:

As you can see, here I also declare using the @EnableR2dbcRepositories annotation. The purpose of this annotation, similar to the @EnableJpaRepositories annotation in Spring Data JPA, will help Spring automatically scan and initialize beans for Spring Data R2DBC Repository classes. Annotation @EnableR2dbcRepositories allows us to configure the package to scan with the basePackages or basePackageClasses attribute, if you do not declare these attributes, by default Spring will scan the package containing the annotated class with the @EnableR2dbcRepositories annotation!

Next, we will define the application-related Repository classes.

As an example, I will define the “student” table:

with the following content in the PostgreSQL database:

The model class for the “student” table, I will define it as follows:

Similar to Spring Data JPA, you can define a Repository class with Spring Data R2DBC for the “student” table as follows:

At this point, we have configured Spring Data R2DBC for our application already!

To check the results, I will write a class with the main() method with the following content:

The result when we run the above example is as follows:

Add Comment