© 2018-2021 The original authors.
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically. |
Preface
The Spring Data R2DBC project applies core Spring concepts to the development of solutions that use the R2DBC drivers for relational databases.
We provide a DatabaseClient
as a high-level abstraction for storing and querying rows.
This document is the reference guide for Spring Data - R2DBC Support. It explains R2DBC module concepts and semantics and.
This section provides some basic introduction to Spring and databases.
1. Learning Spring
Spring Data uses Spring framework’s core functionality, including:
While you need not know the Spring APIs, understanding the concepts behind them is important. At a minimum, the idea behind Inversion of Control (IoC) should be familiar, and you should be familiar with whatever IoC container you choose to use.
You can use the core functionality of the R2DBC support directly, with no need to invoke the IoC services of the Spring Container.
This is much like JdbcTemplate
, which can be used “standalone” without any other services of the Spring container.
To use all the features of Spring Data R2DBC, such as the repository support, you need to configure some parts of the library to use Spring.
To learn more about Spring, refer to the comprehensive documentation that explains the Spring Framework in detail. There are a lot of articles, blog entries, and books on the subject. See the Spring framework home page for more information.
2. What is R2DBC?
R2DBC is the acronym for Reactive Relational Database Connectivity. R2DBC is an API specification initiative that declares a reactive API to be implemented by driver vendors to access their relational databases.
Part of the answer as to why R2DBC was created is the need for a non-blocking application stack to handle concurrency with a small number of threads and scale with fewer hardware resources.
This need cannot be satisfied by reusing standardized relational database access APIs — namely JDBC –- as JDBC is a fully blocking API.
Attempts to compensate for blocking behavior with a ThreadPool
are of limited use.
The other part of the answer is that most applications use a relational database to store their data. While several NoSQL database vendors provide reactive database clients for their databases, migration to NoSQL is not an option for most projects. This was the motivation for a new common API to serve as a foundation for any non-blocking database driver. While the open source ecosystem hosts various non-blocking relational database driver implementations, each client comes with a vendor-specific API, so a generic layer on top of these libraries is not possible.
3. What is Reactive?
The term, “reactive”, refers to programming models that are built around reacting to change, availability, and processability -— network components reacting to I/O events, UI controllers reacting to mouse events, resources being made available, and others. In that sense, non-blocking is reactive, because, instead of being blocked, we are now in the mode of reacting to notifications as operations complete or data becomes available.
There is also another important mechanism that we on the Spring team associate with reactive, and that is non-blocking back pressure. In synchronous, imperative code, blocking calls serve as a natural form of back pressure that forces the caller to wait. In non-blocking code, it becomes essential to control the rate of events so that a fast producer does not overwhelm its destination.
Reactive Streams is a small spec (also adopted in Java 9) that defines the interaction between asynchronous components with back pressure.
For example, a data repository (acting as a Publisher
) can produce data that an HTTP server (acting as a Subscriber
) can then write to the response.
The main purpose of Reactive Streams is to let the subscriber control how quickly or how slowly the publisher produces data.
4. Reactive API
Reactive Streams plays an important role for interoperability. It is of interest to libraries and infrastructure components but less useful as an application API, because it is too low-level. Applications need a higher-level and richer, functional API to compose async logic —- similar to the Java 8 Stream API but not only for tables. This is the role that reactive libraries play.
Project Reactor is the reactive library of choice for Spring Data R2DBC.
It provides the Mono
and Flux
API types to work on data sequences of 0..1
(Mono
) and 0..N
(Flux
) through a rich set of operators aligned with the ReactiveX vocabulary of operators.
Reactor is a Reactive Streams library, and, therefore, all of its operators support non-blocking back pressure.
Reactor has a strong focus on server-side Java. It is developed in close collaboration with Spring.
Spring Data R2DBC requires Project Reactor as a core dependency, but it is interoperable with other reactive libraries through the Reactive Streams specification.
As a general rule, a Spring Data R2DBC repository accepts a plain Publisher
as input, adapts it to a Reactor type internally, uses that, and returns either a Mono
or a Flux
as output.
So, you can pass any Publisher
as input and apply operations on the output, but you need to adapt the output for use with another reactive library.
Whenever feasible, Spring Data adapts transparently to the use of RxJava or another reactive library.
5. Requirements
The Spring Data R2DBC 1.x binaries require:
-
JDK level 8.0 and above
-
Spring Framework 5.3.10 and above
-
R2DBC Arabba-SR10 and above
6. Additional Help Resources
Learning a new framework is not always straightforward. In this section, we try to provide what we think is an easy-to-follow guide for starting with the Spring Data R2DBC module. However, if you encounter issues or you need advice, use one of the following links:
- Community Forum
-
Spring Data on Stack Overflow is a tag for all Spring Data (not just R2DBC) users to share information and help each other. Note that registration is needed only for posting.
- Professional Support
-
Professional, from-the-source support, with guaranteed response time, is available from Pivotal Sofware, Inc., the company behind Spring Data and Spring.
7. Following Development
-
For information on the Spring Data R2DBC source code repository, nightly builds, and snapshot artifacts, see the Spring Data R2DBC home page.
-
You can help make Spring Data best serve the needs of the Spring community by interacting with developers through the community on Stack Overflow.
-
If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data R2DBC issue tracker.
-
To stay up to date with the latest news and announcements in the Spring ecosystem, subscribe to the Spring Community Portal.
-
You can also follow the Spring blog or the Spring Data project team on Twitter (SpringData).
8. Project Metadata
-
Version control: https://github.com/spring-projects/spring-data-r2dbc
-
Bugtracker: https://github.com/spring-projects/spring-data-r2dbc/issues
-
Release repository: https://repo.spring.io/libs-release
-
Milestone repository: https://repo.spring.io/libs-milestone
-
Snapshot repository: https://repo.spring.io/libs-snapshot
9. New & Noteworthy
9.1. What’s New in Spring Data R2DBC 1.3.0
-
Introduce Query by Example support.
9.2. What’s New in Spring Data R2DBC 1.2.0
-
Deprecate Spring Data R2DBC
DatabaseClient
and move off deprecated API in favor of Spring R2DBC. Consult the Migration Guide for further details. -
Support for [entity-callbacks].
-
Auditing through
@EnableR2dbcAuditing
. -
Support for
@Value
in persistence constructors. -
Support for Oracle’s R2DBC driver.
9.3. What’s New in Spring Data R2DBC 1.1.0
-
Introduction of
R2dbcEntityTemplate
for entity-oriented operations. -
Support interface projections with
DatabaseClient.as(…)
. -
Support for
ExecuteFunction
andStatementFilterFunction
viaDatabaseClient.filter(…)
.
9.4. What’s New in Spring Data R2DBC 1.0.0
-
Upgrade to R2DBC 0.8.0.RELEASE.
-
@Modifying
annotation for query methods to consume affected row count. -
Repository
save(…)
with an associated ID completes withTransientDataAccessException
if the row does not exist in the database. -
Added
SingleConnectionConnectionFactory
for testing using connection singletons. -
Support for SpEL expressions in
@Query
. -
ConnectionFactory
routing throughAbstractRoutingConnectionFactory
. -
Utilities for schema initialization through
ResourceDatabasePopulator
andScriptUtils
. -
Propagation and reset of Auto-Commit and Isolation Level control through
TransactionDefinition
. -
Support for Entity-level converters.
-
Kotlin extensions for reified generics and Coroutines.
-
Add pluggable mechanism to register dialects.
-
Support for named parameters.
-
Initial R2DBC support through
DatabaseClient
. -
Initial Transaction support through
TransactionalDatabaseClient
. -
Initial R2DBC Repository Support through
R2dbcRepository
. -
Initial Dialect support for Postgres and Microsoft SQL Server.
Unresolved directive in index.adoc - include::../../../../spring-data-commons/src/main/asciidoc/dependencies.adoc[leveloffset=+1]
Unresolved directive in index.adoc - include::../../../../spring-data-commons/src/main/asciidoc/repositories.adoc[leveloffset=+1]
Reference Documentation
10. Introduction
10.1. Document Structure
This part of the reference documentation explains the core functionality offered by Spring Data R2DBC.
“R2DBC support” introduces the R2DBC module feature set.
“R2DBC Repositories” introduces the repository support for R2DBC.
11. R2DBC support
R2DBC contains a wide range of features:
-
Spring configuration support with Java-based
@Configuration
classes for an R2DBC driver instance. -
R2dbcEntityTemplate
as central class for entity-bound operations that increases productivity when performing common R2DBC operations with integrated object mapping between rows and POJOs. -
Feature-rich object mapping integrated with Spring’s Conversion Service.
-
Annotation-based mapping metadata that is extensible to support other metadata formats.
-
Automatic implementation of Repository interfaces, including support for custom query methods.
For most tasks, you should use R2dbcEntityTemplate
or the repository support, which both use the rich mapping functionality.
R2dbcEntityTemplate
is the place to look for accessing functionality such as ad-hoc CRUD operations.
11.1. Getting Started
An easy way to set up a working environment is to create a Spring-based project through start.spring.io. To do so:
-
Add the following to the pom.xml files
dependencies
element:<dependencyManagement> <dependencies> <dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-bom</artifactId> <version>${r2dbc-releasetrain.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- other dependency elements omitted --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-r2dbc</artifactId> <version>1.4.0-SNAPSHOT</version> </dependency> <!-- a R2DBC driver --> <dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-h2</artifactId> <version>Arabba-SR10</version> </dependency> </dependencies>
-
Change the version of Spring in the pom.xml to be
<spring-framework.version>5.3.10</spring-framework.version>
-
Add the following location of the Spring Milestone repository for Maven to your
pom.xml
such that it is at the same level as your<dependencies/>
element:<repositories> <repository> <id>spring-milestone</id> <name>Spring Maven MILESTONE Repository</name> <url>https://repo.spring.io/libs-milestone</url> </repository> </repositories>
The repository is also browseable here.
You may also want to set the logging level to DEBUG
to see some additional information.
To do so, edit the application.properties
file to have the following content:
logging.level.org.springframework.r2dbc=DEBUG
Then you can, for example, create a Person
class to persist, as follows:
public class Person {
private final String id;
private final String name;
private final int age;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Next, you need to create a table structure in your database, as follows:
CREATE TABLE person
(id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255),
age INT);
You also need a main application to run, as follows:
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.test.StepVerifier;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
public class R2dbcApp {
private static final Log log = LogFactory.getLog(R2dbcApp.class);
public static void main(String[] args) {
ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
R2dbcEntityTemplate template = new R2dbcEntityTemplate(connectionFactory);
template.getDatabaseClient().sql("CREATE TABLE person" +
"(id VARCHAR(255) PRIMARY KEY," +
"name VARCHAR(255)," +
"age INT)")
.fetch()
.rowsUpdated()
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
template.insert(Person.class)
.using(new Person("joe", "Joe", 34))
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
template.select(Person.class)
.first()
.doOnNext(it -> log.info(it))
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
}
}
When you run the main program, the preceding examples produce output similar to the following:
2018-11-28 10:47:03,893 DEBUG amework.core.r2dbc.DefaultDatabaseClient: 310 - Executing SQL statement [CREATE TABLE person
(id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255),
age INT)]
2018-11-28 10:47:04,074 DEBUG amework.core.r2dbc.DefaultDatabaseClient: 908 - Executing SQL statement [INSERT INTO person (id, name, age) VALUES($1, $2, $3)]
2018-11-28 10:47:04,092 DEBUG amework.core.r2dbc.DefaultDatabaseClient: 575 - Executing SQL statement [SELECT id, name, age FROM person]
2018-11-28 10:47:04,436 INFO org.spring.r2dbc.example.R2dbcApp: 43 - Person [id='joe', name='Joe', age=34]
Even in this simple example, there are few things to notice:
-
You can create an instance of the central helper class in Spring Data R2DBC (
R2dbcEntityTemplate
) by using a standardio.r2dbc.spi.ConnectionFactory
object. -
The mapper works against standard POJO objects without the need for any additional metadata (though you can, optionally, provide that information — see here.).
-
Mapping conventions can use field access.Notice that the
Person
class has only getters. -
If the constructor argument names match the column names of the stored row, they are used to instantiate the object.
11.2. Examples Repository
There is a GitHub repository with several examples that you can download and play around with to get a feel for how the library works.
11.3. Connecting to a Relational Database with Spring
One of the first tasks when using relational databases and Spring is to create a io.r2dbc.spi.ConnectionFactory
object by using the IoC container.Make sure to use a supported database and driver.
11.3.1. Registering a ConnectionFactory
Instance using Java-based Metadata
The following example shows an example of using Java-based bean metadata to register an instance of io.r2dbc.spi.ConnectionFactory
:
io.r2dbc.spi.ConnectionFactory
object using Java-based bean metadata@Configuration
public class ApplicationConfiguration extends AbstractR2dbcConfiguration {
@Override
@Bean
public ConnectionFactory connectionFactory() {
return …
}
}
This approach lets you use the standard io.r2dbc.spi.ConnectionFactory
instance, with the container using Spring’s AbstractR2dbcConfiguration
.As compared to registering a ConnectionFactory
instance directly, the configuration support has the added advantage of also providing the container with an ExceptionTranslator
implementation that translates R2DBC exceptions to exceptions in Spring’s portable DataAccessException
hierarchy for data access classes annotated with the @Repository
annotation.This hierarchy and the use of @Repository
is described in Spring’s DAO support features.
AbstractR2dbcConfiguration
also registers DatabaseClient
, which is required for database interaction and for Repository implementation.
11.3.2. R2DBC Drivers
Spring Data R2DBC supports drivers through R2DBC’s pluggable SPI mechanism.
You can use any driver that implements the R2DBC spec with Spring Data R2DBC.
Since Spring Data R2DBC reacts to specific features of each database, it requires a Dialect
implementation otherwise your application won’t start up.
Spring Data R2DBC ships with dialect implementations for the following drivers:
-
H2 (
io.r2dbc:r2dbc-h2
) -
MariaDB (
org.mariadb:r2dbc-mariadb
) -
Microsoft SQL Server (
io.r2dbc:r2dbc-mssql
) -
MySQL (
dev.miku:r2dbc-mysql
) -
jasync-sql MySQL (
com.github.jasync-sql:jasync-r2dbc-mysql
) -
Postgres (
io.r2dbc:r2dbc-postgresql
) -
Oracle (
com.oracle.database.r2dbc:oracle-r2dbc
)
Spring Data R2DBC reacts to database specifics by inspecting the ConnectionFactory
and selects the appropriate database dialect accordingly.
You need to configure your own R2dbcDialect
if the driver you use is not yet known to Spring Data R2DBC.
Dialects are resolved by DialectResolver from a ConnectionFactory , typically by inspecting ConnectionFactoryMetadata .
+ You can let Spring auto-discover your R2dbcDialect by registering a class that implements org.springframework.data.r2dbc.dialect.DialectResolver$R2dbcDialectProvider through META-INF/spring.factories .
DialectResolver discovers dialect provider implementations from the class path using Spring’s SpringFactoriesLoader .
|
11.4. R2dbcEntityOperations Data Access API
R2dbcEntityTemplate
is the central entrypoint for Spring Data R2DBC.
It provides direct entity-oriented methods and a more narrow, fluent interface for typical ad-hoc use-cases, such as querying, inserting, updating, and deleting data.
The entry points (insert()
, select()
, update()
, and others) follow a natural naming schema based on the operation to be run.
Moving on from the entry point, the API is designed to offer only context-dependent methods that lead to a terminating method that creates and runs a SQL statement.
Spring Data R2DBC uses a R2dbcDialect
abstraction to determine bind markers, pagination support and the data types natively supported by the underlying driver.
All terminal methods return always a Publisher type that represents the desired operation.
The actual statements are sent to the database upon subscription.
|
11.4.1. Methods for Inserting and Updating Entities
There are several convenient methods on R2dbcEntityTemplate
for saving and inserting your objects.
To have more fine-grained control over the conversion process, you can register Spring converters with R2dbcCustomConversions
— for example Converter<Person, OutboundRow>
and Converter<Row, Person>
.
The simple case of using the save operation is to save a POJO. In this case, the table name is determined by name (not fully qualified) of the class. You may also call the save operation with a specific collection name. You can use mapping metadata to override the collection in which to store the object.
When inserting or saving, if the Id
property is not set, the assumption is that its value will be auto-generated by the database.
Consequently, for auto-generation the type of the Id
property or field in your class must be a Long
, or Integer
.
The following example shows how to insert a row and retrieving its contents:
R2dbcEntityTemplate
Person person = new Person("John", "Doe");
Mono<Person> saved = template.insert(person);
Mono<Person> loaded = template.selectOne(query(where("firstname").is("John")),
Person.class);
The following insert and update operations are available:
A similar set of insert operations is also available:
-
Mono<T>
insert(T objectToSave)
: Insert the object to the default table. -
Mono<T>
update(T objectToSave)
: Insert the object to the default table.
Table names can be customized by using the fluent API.
11.4.2. Selecting Data
The select(…)
and selectOne(…)
methods on R2dbcEntityTemplate
are used to select data from a table.
Both methods take a Query
object that defines the field projection, the WHERE
clause, the ORDER BY
clause and limit/offset pagination.
Limit/offset functionality is transparent to the application regardless of the underlying database.
This functionality is supported by the R2dbcDialect
abstraction to cater for differences between the individual SQL flavors.
R2dbcEntityTemplate
Flux<Person> loaded = template.select(query(where("firstname").is("John")),
Person.class);
11.4.3. Fluent API
This section explains the fluent API usage. Consider the following simple query:
Flux<Person> people = template.select(Person.class) (1)
.all(); (2)
1 | Using Person with the select(…) method maps tabular results on Person result objects. |
2 | Fetching all() rows returns a Flux<Person> without limiting results. |
The following example declares a more complex query that specifies the table name by name, a WHERE
condition, and an ORDER BY
clause:
Mono<Person> first = template.select(Person.class) (1)
.from("other_person")
.matching(query(where("firstname").is("John") (2)
.and("lastname").in("Doe", "White"))
.sort(by(desc("id")))) (3)
.one(); (4)
1 | Selecting from a table by name returns row results using the given domain type. |
2 | The issued query declares a WHERE condition on firstname and lastname columns to filter results. |
3 | Results can be ordered by individual column names, resulting in an ORDER BY clause. |
4 | Selecting the one result fetches only a single row.
This way of consuming rows expects the query to return exactly a single result.
Mono emits a IncorrectResultSizeDataAccessException if the query yields more than a single result. |
You can directly apply Projections to results by providing the target type via select(Class<?>) .
|
You can switch between retrieving a single entity and retrieving multiple entities through the following terminating methods:
-
first()
: Consume only the first row, returning aMono
. The returnedMono
completes without emitting an object if the query returns no results. -
one()
: Consume exactly one row, returning aMono
. The returnedMono
completes without emitting an object if the query returns no results. If the query returns more than one row,Mono
completes exceptionally emittingIncorrectResultSizeDataAccessException
. -
all()
: Consume all returned rows returning aFlux
. -
count()
: Apply a count projection returningMono<Long>
. -
exists()
: Return whether the query yields any rows by returningMono<Boolean>
.
You can use the select()
entry point to express your SELECT
queries.
The resulting SELECT
queries support the commonly used clauses (WHERE
and ORDER BY
) and support pagination.
The fluent API style let you chain together multiple methods while having easy-to-understand code.
To improve readability, you can use static imports that let you avoid using the 'new' keyword for creating Criteria
instances.
Methods for the Criteria Class
The Criteria
class provides the following methods, all of which correspond to SQL operators:
-
Criteria
and(String column)
: Adds a chainedCriteria
with the specifiedproperty
to the currentCriteria
and returns the newly created one. -
Criteria
or(String column)
: Adds a chainedCriteria
with the specifiedproperty
to the currentCriteria
and returns the newly created one. -
Criteria
greaterThan(Object o)
: Creates a criterion by using the>
operator. -
Criteria
greaterThanOrEquals(Object o)
: Creates a criterion by using the>=
operator. -
Criteria
in(Object… o)
: Creates a criterion by using theIN
operator for a varargs argument. -
Criteria
in(Collection<?> collection)
: Creates a criterion by using theIN
operator using a collection. -
Criteria
is(Object o)
: Creates a criterion by using column matching (property = value
). -
Criteria
isNull()
: Creates a criterion by using theIS NULL
operator. -
Criteria
isNotNull()
: Creates a criterion by using theIS NOT NULL
operator. -
Criteria
lessThan(Object o)
: Creates a criterion by using the<
operator. -
Criteria
lessThanOrEquals(Object o)
: Creates a criterion by using the⇐
operator. -
Criteria
like(Object o)
: Creates a criterion by using theLIKE
operator without escape character processing. -
Criteria
not(Object o)
: Creates a criterion by using the!=
operator. -
Criteria
notIn(Object… o)
: Creates a criterion by using theNOT IN
operator for a varargs argument. -
Criteria
notIn(Collection<?> collection)
: Creates a criterion by using theNOT IN
operator using a collection.
You can use Criteria
with SELECT
, UPDATE
, and DELETE
queries.
11.4.4. Inserting Data
You can use the insert()
entry point to insert data.
Consider the following simple typed insert operation:
Mono<Person> insert = template.insert(Person.class) (1)
.using(new Person("John", "Doe")); (2)
1 | Using Person with the into(…) method sets the INTO table, based on mapping metadata.
It also prepares the insert statement to accept Person objects for inserting. |
2 | Provide a scalar Person object.
Alternatively, you can supply a Publisher to run a stream of INSERT statements.
This method extracts all non-null values and inserts them. |
11.4.5. Updating Data
You can use the update()
entry point to update rows.
Updating data starts by specifying the table to update by accepting Update
specifying assignments.
It also accepts Query
to create a WHERE
clause.
Consider the following simple typed update operation:
Person modified = …
Mono<Integer> update = template.update(Person.class) (1)
.inTable("other_table") (2)
.matching(query(where("firstname").is("John"))) (3)
.apply(update("age", 42)); (4)
1 | Update Person objects and apply mapping based on mapping metadata. |
2 | Set a different table name by calling the inTable(…) method. |
3 | Specify a query that translates into a WHERE clause. |
4 | Apply the Update object.
Set in this case age to 42 and return the number of affected rows. |
11.4.6. Deleting Data
You can use the delete()
entry point to delete rows.
Removing data starts with a specification of the table to delete from and, optionally, accepts a Criteria
to create a WHERE
clause.
Consider the following simple insert operation:
Mono<Integer> delete = template.delete(Person.class) (1)
.from("other_table") (2)
.matching(query(where("firstname").is("John"))) (3)
.all(); (4)
1 | Delete Person objects and apply mapping based on mapping metadata. |
2 | Set a different table name by calling the from(…) method. |
3 | Specify a query that translates into a WHERE clause. |
4 | Apply the delete operation and return the number of affected rows. |
12. R2DBC Repositories
This chapter points out the specialties for repository support for R2DBC. This chapter builds on the core repository support explained in [repositories]. Before reading this chapter, you should have a sound understanding of the basic concepts explained there.
12.1. Usage
To access domain entities stored in a relational database, you can use our sophisticated repository support that eases implementation quite significantly.
To do so, create an interface for your repository.
Consider the following Person
class:
public class Person {
@Id
private Long id;
private String firstname;
private String lastname;
// … getters and setters omitted
}
The following example shows a repository interface for the preceding Person
class:
public interface PersonRepository extends ReactiveCrudRepository<Person, Long> {
// additional custom query methods go here
}
To configure R2DBC repositories, you can use the @EnableR2dbcRepositories
annotation.
If no base package is configured, the infrastructure scans the package of the annotated configuration class.
The following example shows how to use Java configuration for a repository:
@Configuration
@EnableR2dbcRepositories
class ApplicationConfig extends AbstractR2dbcConfiguration {
@Override
public ConnectionFactory connectionFactory() {
return …
}
}
Because our domain repository extends ReactiveCrudRepository
, it provides you with reactive CRUD operations to access the entities.
On top of ReactiveCrudRepository
, there is also ReactiveSortingRepository
, which adds additional sorting functionality similar to that of PagingAndSortingRepository
.
Working with the repository instance is merely a matter of dependency injecting it into a client.
Consequently, you can retrieve all Person
objects with the following code:
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class PersonRepositoryTests {
@Autowired
PersonRepository repository;
@Test
void readsAllEntitiesCorrectly() {
repository.findAll()
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
}
@Test
void readsEntitiesByNameCorrectly() {
repository.findByFirstname("Hello World")
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
}
}
The preceding example creates an application context with Spring’s unit test support, which performs annotation-based dependency injection into test cases.
Inside the test method, we use the repository to query the database.
We use StepVerifier
as a test aid to verify our expectations against the results.
12.2. Query Methods
Most of the data access operations you usually trigger on a repository result in a query being run against the databases. Defining such a query is a matter of declaring a method on the repository interface, as the following example shows:
interface ReactivePersonRepository extends ReactiveSortingRepository<Person, Long> {
Flux<Person> findByFirstname(String firstname); (1)
Flux<Person> findByFirstname(Publisher<String> firstname); (2)
Flux<Person> findByFirstnameOrderByLastname(String firstname, Pageable pageable); (3)
Mono<Person> findByFirstnameAndLastname(String firstname, String lastname); (4)
Mono<Person> findFirstByLastname(String lastname); (5)
@Query("SELECT * FROM person WHERE lastname = :lastname")
Flux<Person> findByLastname(String lastname); (6)
@Query("SELECT firstname, lastname FROM person WHERE lastname = $1")
Mono<Person> findFirstByLastname(String lastname); (7)
}
1 | The method shows a query for all people with the given firstname . The query is derived by parsing the method name for constraints that can be concatenated with And and Or . Thus, the method name results in a query expression of SELECT … FROM person WHERE firstname = :firstname . |
2 | The method shows a query for all people with the given firstname once the firstname is emitted by the given Publisher . |
3 | Use Pageable to pass offset and sorting parameters to the database. |
4 | Find a single entity for the given criteria. It completes with IncorrectResultSizeDataAccessException on non-unique results. |
5 | Unless <4>, the first entity is always emitted even if the query yields more result rows. |
6 | The findByLastname method shows a query for all people with the given last name. |
7 | A query for a single Person entity projecting only firstname and lastname columns.
The annotated query uses native bind markers, which are Postgres bind markers in this example. |
Note that the columns of a select statement used in a @Query
annotation must match the names generated by the NamingStrategy
for the respective property.
If a select statement does not include a matching column, that property is not set. If that property is required by the persistence constructor, either null or (for primitive types) the default value is provided.
The following table shows the keywords that are supported for query methods:
Keyword | Sample | Logical result |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12.2.1. Modifying Queries
The previous sections describe how to declare queries to access a given entity or collection of entities.
Using keywords from the preceding table can be used in conjunction with delete…By
or remove…By
to create derived queries that delete matching rows.
Delete…By
Queryinterface ReactivePersonRepository extends ReactiveSortingRepository<Person, String> {
Mono<Integer> deleteByLastname(String lastname); (1)
Mono<Void> deletePersonByLastname(String lastname); (2)
Mono<Boolean> deletePersonByLastname(String lastname); (3)
}
1 | Using a return type of Mono<Integer> returns the number of affected rows. |
2 | Using Void just reports whether the rows were successfully deleted without emitting a result value. |
3 | Using Boolean reports whether at least one row was removed. |
As this approach is feasible for comprehensive custom functionality, you can modify queries that only need parameter binding by annotating the query method with @Modifying
, as shown in the following example:
@Modifying
@Query("UPDATE person SET firstname = :firstname where lastname = :lastname")
Mono<Integer> setFixedFirstnameFor(String firstname, String lastname);
The result of a modifying query can be:
-
Void
(or KotlinUnit
) to discard update count and await completion. -
Integer
or another numeric type emitting the affected rows count. -
Boolean
to emit whether at least one row was updated.
The @Modifying
annotation is only relevant in combination with the @Query
annotation.
Derived custom methods do not require this annotation.
Alternatively, you can add custom modifying behavior by using the facilities described in Custom Implementations for Spring Data Repositories.
12.2.2. Queries with SpEL Expressions
Query string definitions can be used together with SpEL expressions to create dynamic queries at runtime. SpEL expressions can provide predicate values which are evaluated right before running the query.
Expressions expose method arguments through an array that contains all the arguments.
The following query uses [0]
to declare the predicate value for lastname
(which is equivalent to the :lastname
parameter binding):
@Query("SELECT * FROM person WHERE lastname = :#{[0]}")
Flux<Person> findByQueryWithExpression(String lastname);
SpEL in query strings can be a powerful way to enhance queries. However, they can also accept a broad range of unwanted arguments. You should make sure to sanitize strings before passing them to the query to avoid unwanted changes to your query.
Expression support is extensible through the Query SPI: org.springframework.data.spel.spi.EvaluationContextExtension
.
The Query SPI can contribute properties and functions and can customize the root object.
Extensions are retrieved from the application context at the time of SpEL evaluation when the query is built.
When using SpEL expressions in combination with plain parameters, use named parameter notation instead of native bind markers to ensure a proper binding order. |
12.2.3. Query By Example
Spring Data R2DBC also lets you use Query By Example to fashion queries.
This technique allows you to use a "probe" object.
Essentially, any field that isn’t empty or null
will be used to match.
Here’s an example:
Employee employee = new Employee(); (1)
employee.setName("Frodo");
Example<Employee> example = Example.of(employee); (2)
Flux<Employee> employees = repository.findAll(example); (3)
// do whatever with the flux
1 | Create a domain object with the criteria (null fields will be ignored). |
2 | Using the domain object, create an Example . |
3 | Through the R2dbcRepository , execute query (use findOne for a Mono ). |
This illustrates how to craft a simple probe using a domain object.
In this case, it will query based on the Employee
object’s name
field being equal to Frodo
.
null
fields are ignored.
Employee employee = new Employee();
employee.setName("Baggins");
employee.setRole("ring bearer");
ExampleMatcher matcher = matching() (1)
.withMatcher("name", endsWith()) (2)
.withIncludeNullValues() (3)
.withIgnorePaths("role"); (4)
Example<Employee> example = Example.of(employee, matcher); (5)
Flux<Employee> employees = repository.findAll(example);
// do whatever with the flux
1 | Create a custom ExampleMatcher that matches on ALL fields (use matchingAny() to match on ANY fields) |
2 | For the name field, use a wildcard that matches against the end of the field |
3 | Match columns against null (don’t forget that NULL doesn’t equal NULL in relational databases). |
4 | Ignore the role field when forming the query. |
5 | Plug the custom ExampleMatcher into the probe. |
It’s also possible to apply a withTransform()
against any property, allowing you to transform a property before forming the query.
For example, you can apply a toUpperCase()
to a String
-based property before the query is created.
Query By Example really shines when you you don’t know all the fields needed in a query in advance. If you were building a filter on a web page where the user can pick the fields, Query By Example is a great way to flexibly capture that into an efficient query.
Unresolved directive in reference/r2dbc-repositories.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/is-new-state-detection.adoc[leveloffset=+2]
12.2.4. ID Generation
Spring Data R2DBC uses the ID to identify entities.
The ID of an entity must be annotated with Spring Data’s @Id
annotation.
When your database has an auto-increment column for the ID column, the generated value gets set in the entity after inserting it into the database.
Spring Data R2DBC does not attempt to insert values of identifier columns when the entity is new and the identifier value defaults to its initial value.
That is 0
for primitive types and null
if the identifier property uses a numeric wrapper type such as Long
.
One important constraint is that, after saving an entity, the entity must not be new anymore. Note that whether an entity is new is part of the entity’s state. With auto-increment columns, this happens automatically, because the ID gets set by Spring Data with the value from the ID column.
12.2.5. Optimistic Locking
The @Version
annotation provides syntax similar to that of JPA in the context of R2DBC and makes sure updates are only applied to rows with a matching version.
Therefore, the actual value of the version property is added to the update query in such a way that the update does not have any effect if another operation altered the row in the meantime.
In that case, an OptimisticLockingFailureException
is thrown.
The following example shows these features:
@Table
class Person {
@Id Long id;
String firstname;
String lastname;
@Version Long version;
}
R2dbcEntityTemplate template = …;
Mono<Person> daenerys = template.insert(new Person("Daenerys")); (1)
Person other = template.select(Person.class)
.matching(query(where("id").is(daenerys.getId())))
.first().block(); (2)
daenerys.setLastname("Targaryen");
template.update(daenerys); (3)
template.update(other).subscribe(); // emits OptimisticLockingFailureException (4)
1 | Initially insert row. version is set to 0 . |
2 | Load the just inserted row. version is still 0 . |
3 | Update the row with version = 0 .Set the lastname and bump version to 1 . |
4 | Try to update the previously loaded row that still has version = 0 .The operation fails with an OptimisticLockingFailureException , as the current version is 1 . |
Unresolved directive in reference/r2dbc-repositories.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/repository-projections.adoc[leveloffset=+2]
Result Mapping
A query method returning an Interface- or DTO projection is backed by results produced by the actual query.
Interface projections generally rely on mapping results onto the domain type first to consider potential @Column
type mappings and the actual projection proxy uses a potentially partially materialized entity to expose projection data.
Result mapping for DTO projections depends on the actual query type. Derived queries use the domain type to map results, and Spring Data creates DTO instances solely from properties available on the domain type. Declaring properties in your DTO that are not available on the domain type is not supported.
String-based queries use a different approach since the actual query, specifically the field projection, and result type declaration are close together.
DTO projections used with query methods annotated with @Query
map query results directly into the DTO type.
Field mappings on the domain type are not considered.
Using the DTO type directly, your query method can benefit from a more dynamic projection that isn’t restricted to the domain model.
Unresolved directive in reference/r2dbc-repositories.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/entity-callbacks.adoc[leveloffset=+1] :leveloffset: +2
13. Store specific EntityCallbacks
Spring Data R2DBC uses the EntityCallback
API for its auditing support and reacts on the following callbacks.
Callback | Method | Description | Order |
---|---|---|---|
BeforeConvertCallback |
|
Invoked before a domain object is converted to |
|
AfterConvertCallback |
|
Invoked after a domain object is loaded. |
|
AuditingEntityCallback |
|
Marks an auditable entity created or modified |
100 |
BeforeSaveCallback |
|
Invoked before a domain object is saved. |
|
AfterSaveCallback |
|
Invoked after a domain object is saved. |
|
13.1. Working with multiple Databases
When working with multiple, potentially different databases, your application will require a different approach to configuration.
The provided AbstractR2dbcConfiguration
support class assumes a single ConnectionFactory
from which the Dialect
gets derived.
That being said, you need to define a few beans yourself to configure Spring Data R2DBC to work with multiple databases.
R2DBC repositories require R2dbcEntityOperations
to implement repositories.
A simple configuration to scan for repositories without using AbstractR2dbcConfiguration
looks like:
@Configuration
@EnableR2dbcRepositories(basePackages = "com.acme.mysql", entityOperationsRef = "mysqlR2dbcEntityOperations")
static class MySQLConfiguration {
@Bean
@Qualifier("mysql")
public ConnectionFactory mysqlConnectionFactory() {
return …
}
@Bean
public R2dbcEntityOperations mysqlR2dbcEntityOperations(@Qualifier("mysql") ConnectionFactory connectionFactory) {
DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);
return new R2dbcEntityTemplate(databaseClient, MySqlDialect.INSTANCE);
}
}
Note that @EnableR2dbcRepositories
allows configuration either through databaseClientRef
or entityOperationsRef
.
Using various DatabaseClient
beans is useful when connecting to multiple databases of the same type.
When using different database systems that differ in their dialect, use @EnableR2dbcRepositories
(entityOperationsRef = …)` instead.
Unresolved directive in index.adoc - include::../../../../spring-data-commons/src/main/asciidoc/auditing.adoc[leveloffset=+1]
13.2. General Auditing Configuration for R2DBC
Since Spring Data R2DBC 1.2, auditing can be enabled by annotating a configuration class with the @EnableR2dbcAuditing
annotation, as the following example shows:
@Configuration
@EnableR2dbcAuditing
class Config {
@Bean
public ReactiveAuditorAware<AuditableUser> myAuditorProvider() {
return new AuditorAwareImpl();
}
}
If you expose a bean of type ReactiveAuditorAware
to the ApplicationContext
, the auditing infrastructure picks it up automatically and uses it to determine the current user to be set on domain types.
If you have multiple implementations registered in the ApplicationContext
, you can select the one to be used by explicitly setting the auditorAwareRef
attribute of @EnableR2dbcAuditing
.
14. Mapping
Rich mapping support is provided by the MappingR2dbcConverter
. MappingR2dbcConverter
has a rich metadata model that allows mapping domain objects to a data row.
The mapping metadata model is populated by using annotations on your domain objects.
However, the infrastructure is not limited to using annotations as the only source of metadata information.
The MappingR2dbcConverter
also lets you map objects to rows without providing any additional metadata, by following a set of conventions.
This section describes the features of the MappingR2dbcConverter
, including how to use conventions for mapping objects to rows and how to override those conventions with annotation-based mapping metadata.
Unresolved directive in reference/mapping.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/object-mapping.adoc[leveloffset=+1]
14.1. Convention-based Mapping
MappingR2dbcConverter
has a few conventions for mapping objects to rows when no additional mapping metadata is provided.
The conventions are:
-
The short Java class name is mapped to the table name in the following manner. The
com.bigbank.SavingsAccount
class maps to theSAVINGS_ACCOUNT
table name. The same name mapping is applied for mapping fields to column names. For example, thefirstName
field maps to theFIRST_NAME
column. You can control this mapping by providing a customNamingStrategy
. See Mapping Configuration for more detail. Table and column names that are derived from property or class names are used in SQL statements without quotes by default. You can control this behavior by settingR2dbcMappingContext.setForceQuote(true)
. -
Nested objects are not supported.
-
The converter uses any Spring Converters registered with it to override the default mapping of object properties to row columns and values.
-
The fields of an object are used to convert to and from columns in the row. Public
JavaBean
properties are not used. -
If you have a single non-zero-argument constructor whose constructor argument names match top-level column names of the row, that constructor is used. Otherwise, the zero-argument constructor is used. If there is more than one non-zero-argument constructor, an exception is thrown.
14.2. Mapping Configuration
By default (unless explicitly configured) an instance of MappingR2dbcConverter
is created when you create a DatabaseClient
.
You can create your own instance of the MappingR2dbcConverter
.
By creating your own instance, you can register Spring converters to map specific classes to and from the database.
You can configure the MappingR2dbcConverter
as well as DatabaseClient
and ConnectionFactory
by using Java-based metadata. The following example uses Spring’s Java-based configuration:
If you set setForceQuote
of the R2dbcMappingContext to
true, table and column names derived from classes and properties are used with database specific quotes.
This means that it is OK to use reserved SQL words (such as order) in these names.
You can do so by overriding r2dbcMappingContext(Optional<NamingStrategy>)
of AbstractR2dbcConfiguration
.
Spring Data converts the letter casing of such a name to that form which is also used by the configured database when no quoting is used.
Therefore, you can use unquoted names when creating tables, as long as you do not use keywords or special characters in your names.
For databases that adhere to the SQL standard, this means that names are converted to upper case.
The quoting character and the way names get capitalized is controlled by the used Dialect
.
See R2DBC Drivers for how to configure custom dialects.
@Configuration
public class MyAppConfig extends AbstractR2dbcConfiguration {
public ConnectionFactory connectionFactory() {
return ConnectionFactories.get("r2dbc:…");
}
// the following are optional
@Override
protected List<Object> getCustomConverters() {
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new org.springframework.data.r2dbc.test.PersonReadConverter());
converterList.add(new org.springframework.data.r2dbc.test.PersonWriteConverter());
return converterList;
}
}
AbstractR2dbcConfiguration
requires you to implement a method that defines a ConnectionFactory
.
You can add additional converters to the converter by overriding the r2dbcCustomConversions
method.
You can configure a custom NamingStrategy
by registering it as a bean.
The NamingStrategy
controls how the names of classes and properties get converted to the names of tables and columns.
AbstractR2dbcConfiguration creates a DatabaseClient instance and registers it with the container under the name of databaseClient .
|
14.3. Metadata-based Mapping
To take full advantage of the object mapping functionality inside the Spring Data R2DBC support, you should annotate your mapped objects with the @Table
annotation.
Although it is not necessary for the mapping framework to have this annotation (your POJOs are mapped correctly, even without any annotations), it lets the classpath scanner find and pre-process your domain objects to extract the necessary metadata.
If you do not use this annotation, your application takes a slight performance hit the first time you store a domain object, because the mapping framework needs to build up its internal metadata model so that it knows about the properties of your domain object and how to persist them.
The following example shows a domain object:
package com.mycompany.domain;
@Table
public class Person {
@Id
private Long id;
private Integer ssn;
private String firstName;
private String lastName;
}
The @Id annotation tells the mapper which property you want to use as the primary key.
|
14.3.1. Default Type Mapping
The following table explains how property types of an entity affect mapping:
Source Type | Target Type | Remarks |
---|---|---|
Primitive types and wrapper types |
Passthru |
Can be customized using Explicit Converters. |
JSR-310 Date/Time types |
Passthru |
Can be customized using Explicit Converters. |
|
Passthru |
Can be customized using Explicit Converters. |
|
String |
Can be customized by registering a Explicit Converters. |
|
Passthru |
Can be customized using Explicit Converters. |
|
Passthru |
Considered a binary payload. |
|
Array of |
Conversion to Array type if supported by the configured driver, not supported otherwise. |
Arrays of primitive types, wrapper types and |
Array of wrapper type (e.g. |
Conversion to Array type if supported by the configured driver, not supported otherwise. |
Driver-specific types |
Passthru |
Contributed as a simple type by the used |
Complex objects |
Target type depends on registered |
Requires a Explicit Converters, not supported otherwise. |
The native data type for a column depends on the R2DBC driver type mapping. Drivers can contribute additional simple types such as Geometry types. |
14.3.2. Mapping Annotation Overview
The MappingR2dbcConverter
can use metadata to drive the mapping of objects to rows.
The following annotations are available:
-
@Id
: Applied at the field level to mark the primary key. -
@Table
: Applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the table where the database is stored. -
@Transient
: By default, all fields are mapped to the row. This annotation excludes the field where it is applied from being stored in the database. Transient properties cannot be used within a persistence constructor as the converter cannot materialize a value for the constructor argument. -
@PersistenceConstructor
: Marks a given constructor — even a package protected one — to use when instantiating the object from the database. Constructor arguments are mapped by name to the values in the retrieved row. -
@Value
: This annotation is part of the Spring Framework. Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key’s value retrieved in the database before it is used to construct a domain object. In order to reference a column of a given row one has to use expressions like:@Value("#root.myProperty")
where root refers to the root of the givenRow
. -
@Column
: Applied at the field level to describe the name of the column as it is represented in the row, letting the name be different from the field name of the class. Names specified with a@Column
annotation are always quoted when used in SQL statements. For most databases, this means that these names are case-sensitive. It also means that you can use special characters in these names. However, this is not recommended, since it may cause problems with other tools. -
@Version
: Applied at field level is used for optimistic locking and checked for modification on save operations. The value isnull
(zero
for primitive types) is considered as marker for entities to be new. The initially stored value iszero
(one
for primitive types). The version gets incremented automatically on every update. See Optimistic Locking for further reference.
The mapping metadata infrastructure is defined in the separate spring-data-commons
project that is technology-agnostic.
Specific subclasses are used in the R2DBC support to support annotation based metadata.
Other strategies can also be put in place (if there is demand).
14.3.3. Customized Object Construction
The mapping subsystem allows the customization of the object construction by annotating a constructor with the @PersistenceConstructor
annotation.The values to be used for the constructor parameters are resolved in the following way:
-
If a parameter is annotated with the
@Value
annotation, the given expression is evaluated, and the result is used as the parameter value. -
If the Java type has a property whose name matches the given field of the input row, then its property information is used to select the appropriate constructor parameter to which to pass the input field value. This works only if the parameter name information is present in the Java
.class
files, which you can achieve by compiling the source with debug information or using the-parameters
command-line switch forjavac
in Java 8. -
Otherwise, a
MappingException
is thrown to indicate that the given constructor parameter could not be bound.
class OrderItem {
private @Id final String id;
private final int quantity;
private final double unitPrice;
OrderItem(String id, int quantity, double unitPrice) {
this.id = id;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
// getters/setters ommitted
}
14.3.4. Overriding Mapping with Explicit Converters
When storing and querying your objects, it is often convenient to have a R2dbcConverter
instance to handle the mapping of all Java types to OutboundRow
instances.
However, you may sometimes want the R2dbcConverter
instances to do most of the work but let you selectively handle the conversion for a particular type — perhaps to optimize performance.
To selectively handle the conversion yourself, register one or more one or more org.springframework.core.convert.converter.Converter
instances with the R2dbcConverter
.
You can use the r2dbcCustomConversions
method in AbstractR2dbcConfiguration
to configure converters.
The examples at the beginning of this chapter show how to perform the configuration with Java.
Custom top-level entity conversion requires asymmetric types for conversion.
Inbound data is extracted from R2DBC’s Row .
Outbound data (to be used with INSERT /UPDATE statements) is represented as OutboundRow and later assembled to a statement.
|
The following example of a Spring Converter implementation converts from a Row
to a Person
POJO:
@ReadingConverter
public class PersonReadConverter implements Converter<Row, Person> {
public Person convert(Row source) {
Person p = new Person(source.get("id", String.class),source.get("name", String.class));
p.setAge(source.get("age", Integer.class));
return p;
}
}
Please note that converters get applied on singular properties.
Collection properties (e.g. Collection<Person>
) are iterated and converted element-wise.
Collection converters (e.g. Converter<List<Person>>, OutboundRow
) are not supported.
R2DBC uses boxed primitives (Integer.class instead of int.class ) to return primitive values.
|
The following example converts from a Person
to a OutboundRow
:
@WritingConverter
public class PersonWriteConverter implements Converter<Person, OutboundRow> {
public OutboundRow convert(Person source) {
OutboundRow row = new OutboundRow();
row.put("id", SettableValue.from(source.getId()));
row.put("name", SettableValue.from(source.getFirstName()));
row.put("age", SettableValue.from(source.getAge()));
return row;
}
}
Overriding Enum Mapping with Explicit Converters
Some databases, such as Postgres, can natively write enum values using their database-specific enumerated column type.
Spring Data converts Enum
values by default to String
values for maximum portability.
To retain the actual enum value, register a @Writing
converter whose source and target types use the actual enum type to avoid using Enum.name()
conversion.
Additionally, you need to configure the enum type on the driver level so that the driver is aware how to represent the enum type.
The following example shows the involved components to read and write Color
enum values natively:
enum Color {
Grey, Blue
}
class ColorConverter extends EnumWriteSupport<Color> {
}
class Product {
@Id long id;
Color color;
// …
}
Unresolved directive in reference/kotlin.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/kotlin.adoc[]
Unresolved directive in reference/kotlin.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/kotlin-extensions.adoc[leveloffset=+1]
To retrieve a list of SWCharacter
objects in Java, you would normally write the following:
Flux<SWCharacter> characters = client.select().from(SWCharacter.class).fetch().all();
With Kotlin and the Spring Data extensions, you can instead write the following:
val characters = client.select().from<SWCharacter>().fetch().all()
// or (both are equivalent)
val characters : Flux<SWCharacter> = client.select().from().fetch().all()
As in Java, characters
in Kotlin is strongly typed, but Kotlin’s clever type inference allows for shorter syntax.
Spring Data R2DBC provides the following extensions:
-
Reified generics support for
DatabaseClient
andCriteria
. -
[kotlin.coroutines] extensions for
DatabaseClient
.
Unresolved directive in reference/kotlin.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/kotlin-coroutines.adoc[leveloffset=+1]
Appendix
Appendix A: Migration Guide
The following sections explain how to migrate to a newer version of Spring Data R2DBC.
Upgrading from 1.1.x to 1.2.x
Spring Data R2DBC was developed with the intent to evaluate how well R2DBC can integrate with Spring applications.
One of the main aspects was to move core support into Spring Framework once R2DBC support has proven useful.
Spring Framework 5.3 ships with a new module: Spring R2DBC (spring-r2dbc
).
spring-r2dbc
ships core R2DBC functionality (a slim variant of DatabaseClient
, Transaction Manager, Connection Factory initialization, Exception translation) that was initially provided by Spring Data R2DBC.
The 1.2.0 release aligns with what’s provided in Spring R2DBC by making several changes outlined in the following sections.
Spring R2DBC’s DatabaseClient
is a more lightweight implementation that encapsulates a pure SQL-oriented interface.
You will notice that the method to run SQL statements changed from DatabaseClient.execute(…)
to DatabaseClient.sql(…)
.
The fluent API for CRUD operations has moved into R2dbcEntityTemplate
.
If you use logging of SQL statements through the logger prefix org.springframework.data.r2dbc
, make sure to update it to org.springframework.r2dbc
(that is removing .data
) to point to Spring R2DBC components.
Deprecations
-
Deprecation of
o.s.d.r2dbc.core.DatabaseClient
and its support classesConnectionAccessor
,FetchSpec
,SqlProvider
and a few more. Named parameter support classes such asNamedParameterExpander
are encapsulated by Spring R2DBC’sDatabaseClient
implementation hence we’re not providing replacements as this was internal API in the first place. Useo.s.r2dbc.core.DatabaseClient
and their Spring R2DBC replacements available fromorg.springframework.r2dbc.core
. Entity-based methods (select
/insert
/update
/delete
) methods are available throughR2dbcEntityTemplate
which was introduced with version 1.1. -
Deprecation of
o.s.d.r2dbc.connectionfactory
,o.s.d.r2dbc.connectionfactory.init
, ando.s.d.r2dbc.connectionfactory.lookup
packages. Use Spring R2DBC’s variant which you can find ato.s.r2dbc.connection
. -
Deprecation of
o.s.d.r2dbc.convert.ColumnMapRowMapper
. Useo.s.r2dbc.core.ColumnMapRowMapper
instead. -
Deprecation of binding support classes
o.s.d.r2dbc.dialect.Bindings
,BindMarker
,BindMarkers
,BindMarkersFactory
and related types. Use replacements fromorg.springframework.r2dbc.core.binding
. -
Deprecation of
BadSqlGrammarException
,UncategorizedR2dbcException
and exception translation ato.s.d.r2dbc.support
. Spring R2DBC provides a slim exception translation variant without an SPI for now available througho.s.r2dbc.connection.ConnectionFactoryUtils#convertR2dbcException
.
Usage of replacements provided by Spring R2DBC
To ease migration, several deprecated types are now subtypes of their replacements provided by Spring R2DBC. Spring Data R2DBC has changes several methods or introduced new methods accepting Spring R2DBC types. Specifically the following classes are changed:
-
R2dbcEntityTemplate
-
R2dbcDialect
-
Types in
org.springframework.data.r2dbc.query
We recommend that you review and update your imports if you work with these types directly.
Breaking Changes
-
OutboundRow
and statement mappers switched from usingSettableValue
toParameter
-
Repository factory support requires
o.s.r2dbc.core.DatabaseClient
instead ofo.s.data.r2dbc.core.DatabaseClient
.