This guide walks you through the process of building an application that uses Spring Data R2DBC to store and retrieve data in a relational database using reactive database drivers.
You will build an application that stores Customer
POJOs (Plain Old Java Objects) in a memory-based database.
You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
-
Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
-
Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
-
Click Dependencies and select Spring Data R2DBC and H2 Database.
-
Click Generate.
-
Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
Note
|
If your IDE has the Spring Initializr integration, you can complete this process from your IDE. |
Note
|
You can also fork the project from Github and open it in your IDE or other editor. |
In this example, you store Customer
objects, each annotated as a R2DBC entity. The
following listing shows the SQL schema class (in src/main/resources/schema.sql
):
link:complete/src/main/resources/schema.sql[role=include]
Here you have a customer
table with three columns: id
, first_name
, and last_name
.
The id
column is auto-incremented, the other columns follow the default snake case naming scheme.
Later on, we need to register a ConnectionFactoryInitializer
to pick up the schema.sql
file during application startup to initialize the database schema.
Because the H2 driver is on the class path and we haven’t specified a connection URL, Spring Boot starts an embedded H2 database.
In this example, you store Customer
objects, each annotated as a R2DBC entity. The
following listing shows the Customer class (in
src/main/java/com/example/accessingdatar2dbc/Customer.java
):
link:complete/src/main/java/com/example/accessingdatar2dbc/Customer.java[role=include]
Here you have a Customer
class with three attributes: id
, firstName
, and lastName
.
The Customer
class is minimally annotated. The id
property is annotated with @Id
so that Spring Data R2DBC can identify the primary key.
By default, primary keys are assumed to be generated by the database on INSERT
.
The other two properties, firstName
and lastName
, are left unannotated. It is assumed
that they are mapped to columns that share the same names as the properties themselves.
The convenient toString()
method print outs the customer’s properties.
Spring Data R2DBC focuses on using R2DBC as underlying technology to store data in a relational database. Its most compelling feature is the ability to create repository implementations, at runtime, from a repository interface.
To see how this works, create a repository interface that works with Customer
entities
as the following listing (in src/main/java/com/example/accessingdatar2dbc/CustomerRepository.java
) shows:
link:complete/src/main/java/com/example/accessingdatar2dbc/CustomerRepository.java[role=include]
CustomerRepository
extends the ReactiveCrudRepository
interface. The type of entity and ID that it works with, Customer
and Long
, are specified in the generic parameters on ReactiveCrudRepository
.
By extending ReactiveCrudRepository
, CustomerRepository
inherits several methods for working with Customer
persistence, including methods for saving, deleting, and finding Customer
entities using reactive types.
Spring Data R2DBC also lets you define other query methods by annotating these with @Query
.
For example, CustomerRepository
includes the findByLastName()
method.
In a typical Java application, you might expect to write a class that implements CustomerRepository
.
However, that is what makes Spring Data R2DBC so powerful: You need not write an implementation of the repository interface.
Spring Data R2DBC creates an implementation when you run the application.
Now you can wire up this example and see what it looks like!
Spring Initializr creates a simple class for the application. The following listing shows
the class that Initializr created for this example (in
src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java
):
link:initial/src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java[role=include]
Now you need to modify the simple class that the Initializr created for you.
To get output (to the console, in this example), you need to set up a logger.
Then you need to set up the initializer to setup the schema and some data and use it to generate output.
The following listing shows the finished AccessingDataR2dbcApplication
class (in src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java
):
link:complete/src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java[role=include]
The AccessingDataR2dbcApplication
class includes a main()
method that puts the CustomerRepository
through a few tests.
First, it fetches the CustomerRepository
from the Spring application context.
Then it saves a handful of Customer
objects, demonstrating the save()
method and setting up some data to use.
Next, it calls findAll()
to fetch all Customer
objects from the database.
Then it calls findById()
to fetch a single Customer
by its ID.
Finally, it calls findByLastName()
to find all customers whose last name is "Bauer".
R2DBC is a reactive programming technology.
At the same time we’re using it in a synchronized, imperative flow and that is why we’re required to synchronize each call with a variant of the block(…)
method.
In a typical reactive application, the resulting Mono
or Flux
would represent a pipeline of operators that is handed back to a web controller or event processor that subscribes to the reactive sequence without blocking the calling thread.
Note
|
By default, Spring Boot enables R2DBC repository support and looks in the package (and its subpackages) where @SpringBootApplication is located.
If your configuration has R2DBC repository interface definitions located in a package that is not visible, you can point out alternate packages by using @EnableR2dbcRepositories and its type-safe basePackageClasses=MyRepository.class parameter.
|
When you run your application, you should see output similar to the following:
== Customers found with findAll(): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=2, firstName='Chloe', lastName='O'Brian'] Customer[id=3, firstName='Kim', lastName='Bauer'] Customer[id=4, firstName='David', lastName='Palmer'] Customer[id=5, firstName='Michelle', lastName='Dessler'] == Customer found with findOne(1L): Customer[id=1, firstName='Jack', lastName='Bauer'] == Customer found with findByLastName('Bauer'): Customer[id=1, firstName='Jack', lastName='Bauer'] Customer[id=3, firstName='Kim', lastName='Bauer']
Congratulations! You have written a simple application that uses Spring Data R2DBC to save objects to and fetch them from a database, all without writing a concrete repository implementation.
The following guides may also be helpful: