Spring Data R2DBC is a Spring Data module that enables reactive, non-blocking database access for relational databases using Mono and Flux. Unlike JDBC or JPA, it avoids blocking calls, making applications more scalable and high-performing.
- Reactive Model: Uses non-blocking APIs with Mono and Flux
- High Performance: Efficiently handles large concurrent requests
- Scalable: Well-suited for microservices and cloud-native systems
- Event-Driven: Ideal for real-time and asynchronous workflows
- Database Support: Works with R2DBC-supported databases like PostgreSQL and MySQL
Prerequisites
- Java 17 or higher
- Spring Framework 6.0.11 or higher
- R2DBC and above
- A database that supports R2DBC, such as PostgreSQL, MySQL, or MongoDB
Dependencies
Maven Dependencies:
Gradle Dependencies:
Basic steps to connect a database to a Spring Data R2DBC Application
1. Add R2DBC driver dependency in pom.xml. For example for Postgres:
2. Define database configuration properties in application.properties:
3. Autowire ConnectionFactory in a configuration class:
4. Define entity classes and repository interfaces:
5. Autowire repository in a service class:
6. Run the application. Spring Data R2DBC will autoconfigure the connection:
7. Invoke repository methods from service classes to perform CRUD operations:
Step-by-Step Implementation
Step 1: Create Spring Boot Project
- Use Spring Initializr
- Select dependencies: Spring Web , Spring Data R2DBC and PostgreSQL Driver (or your DB)
- R2DBC = Reactive (Non-blocking DB access)
Step 2: Add Dependencies
- Add R2DBC + database driver
- Example: PostgreSQL
Maven
Gradle
Step 3: Configure Database
- Configure DB connection in application.properties
- Use R2DBC URL (not JDBC)
spring.r2dbc.url=r2dbc:postgresql://localhost:5432/testdb
spring.r2dbc.username=postgres
spring.r2dbc.password=admin
Step 4: Create Entity Class
- Represents table in database
- Use R2DBC annotations
Employee.java
Step 5: Create Repository Interface
- Extends ReactiveCrudRepository
- Provides CRUD methods automatically
Step 6: Create Service Class
- Contains business logic
- Uses repository methods
Step 7: Create Controller
- Exposes REST APIs
- Calls service methods
Step 8: Run Application
- Spring Boot auto-configures R2DBC
- No manual connection handling required
- Application starts on default port (8080)