© 2018-2020 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.


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:

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

9. New & Noteworthy

9.1. 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.

9.2. What’s New in Spring Data R2DBC 1.1.0

9.3. 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 with TransientDataAccessException if the row does not exist in the database.

  • Added SingleConnectionConnectionFactory for testing using connection singletons.

  • Support for SpEL expressions in @Query.

  • ConnectionFactory routing through AbstractRoutingConnectionFactory.

  • Utilities for schema initialization through ResourceDatabasePopulator and ScriptUtils.

  • 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:

  1. Add the following to the pom.xml files dependencies element:

      <!-- other dependency elements omitted -->
      <!-- a R2DBC driver -->
  2. Change the version of Spring in the pom.xml to be

  3. 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:

        <name>Spring Maven MILESTONE Repository</name>

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:


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;

  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
// end::class[]}

Next, you need to create a table structure in your database, as follows:

   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)")

      .using(new Person("joe", "Joe", 34))

      .doOnNext(it -> log.info(it))

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
   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 standard io.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:

Example 1. Registering a io.r2dbc.spi.ConnectionFactory object using Java-based bean metadata
public class ApplicationConfiguration extends AbstractR2dbcConfiguration {

  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 impelemtations for the following drivers:

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:

Example 2. Inserting and retrieving entities using the R2dbcEntityTemplate
Person person = new Person("John", "Doe");

Mono<Person> saved = template.insert(person);
Mono<Person> loaded = template.selectOne(query(where("firstname").is("John")),

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.

Example 3. Selecting entities using the R2dbcEntityTemplate
Flux<Person> loaded = template.select(query(where("firstname").is("John")),

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)
1 Using Person with the from(…) method sets the FROM table based on mapping metadata. It also 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)
  .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 a Mono. The returned Mono completes without emitting an object if the query returns no results.

  • one(): Consume exactly one row, returning a Mono. The returned Mono completes without emitting an object if the query returns no results. If the query returns more than one row, Mono completes exceptionally emitting IncorrectResultSizeDataAccessException.

  • all(): Consume all returned rows returning a Flux.

  • count(): Apply a count projection returning Mono<Long>.

  • exists(): Return whether the query yields any rows by returning Mono<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 chained Criteria with the specified property to the current Criteria and returns the newly created one.

  • Criteria or (String column): Adds a chained Criteria with the specified property to the current Criteria 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 the IN operator for a varargs argument.

  • Criteria in (Collection<?> collection): Creates a criterion by using the IN operator using a collection.

  • Criteria is (Object o): Creates a criterion by using column matching (property = value).

  • Criteria isNull (): Creates a criterion by using the IS NULL operator.

  • Criteria isNotNull (): Creates a criterion by using the IS 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 the LIKE 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 the NOT IN operator for a varargs argument.

  • Criteria notIn (Collection<?> collection): Creates a criterion by using the NOT 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:

Example 4. Sample Person entity
public class Person {

  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:

Example 5. Basic repository interface to persist Person entities
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:

Example 6. Java configuration for repositories
class ApplicationConfig extends AbstractR2dbcConfiguration {

  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:

Example 7. Paging access to Person entities
class PersonRepositoryTests {

  PersonRepository repository;

  void readsAllEntitiesCorrectly() {


  void readsEntitiesByNameCorrectly() {

    repository.findByFirstname("Hello World")

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:

Example 8. PersonRepository with query methods
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 lastname. 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.

The following table shows the keywords that are supported for query methods:

Table 1. Supported keywords for query methods
Keyword Sample Logical result


findByBirthdateAfter(Date date)

birthdate > date


findByAgeGreaterThan(int age)

age > age


findByAgeGreaterThanEqual(int age)

age >= age


findByBirthdateBefore(Date date)

birthdate < date


findByAgeLessThan(int age)

age < age


findByAgeLessThanEqual(int age)

age <= age


findByAgeBetween(int from, int to)

age BETWEEN from AND to


findByAgeNotBetween(int from, int to)

age NOT BETWEEN from AND to


findByAgeIn(Collection<Integer> ages)

age IN (age1, age2, ageN)


findByAgeNotIn(Collection ages)

age NOT IN (age1, age2, ageN)

IsNotNull, NotNull


firstname IS NOT NULL

IsNull, Null


firstname IS NULL

Like, StartingWith, EndingWith

findByFirstnameLike(String name)

firstname LIKE name

NotLike, IsNotLike

findByFirstnameNotLike(String name)

firstname NOT LIKE name

Containing on String

findByFirstnameContaining(String name)

firstname LIKE '%' + name +'%'

NotContaining on String

findByFirstnameNotContaining(String name)

firstname NOT LIKE '%' + name +'%'

(No keyword)

findByFirstname(String name)

firstname = name


findByFirstnameNot(String name)

firstname != name

IsTrue, True


active IS TRUE

IsFalse, False


active IS FALSE

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.

Example 9. Delete…By Query
interface 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:

@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 Kotlin Unit) 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. Entity State Detection Strategies

The following table describes the strategies that Spring Data R2DBC offers for detecting whether an entity is new:

Table 2. Options for detection whether an entity is new in Spring Data R2DBC

Id-Property inspection (the default)

By default, the save() method inspects the identifier property of the given entity. If the identifier property is null, then the entity is assumed to be new. Otherwise, it is assumed exist in the datbase.

Implementing Persistable

If an entity implements Persistable, Spring Data R2DBC delegates the new detection to the isNew(…) method of the entity. See the Javadoc for details.

Optimistic Locking through @Version

If an entity uses Optimistic Locking by (version property annotated with @Version), Spring Data R2DBC checks if the entity is new by inspecting the version property whether its value corresponds with Java’s default initialization value. That is 0 for primitive types and null for wrapper types.

Implementing EntityInformation

You can customize the EntityInformation abstraction used in SimpleR2dbcRepository by creating a subclass of R2dbcRepositoryFactory and overriding getEntityInformation(…). You then have to register the custom implementation of R2dbcRepositoryFactory as a Spring bean. Note that this should rarely be necessary. See the Javadoc for details.

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:

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)
                 .first().block();                                                    (2)

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.

Table 3. Supported Entity Callbacks
Callback Method Description Order


onBeforeConvert(T entity, SqlIdentifier table)

Invoked before a domain object is converted to OutboundRow.



onAfterConvert(T entity, SqlIdentifier table)

Invoked after a domain object is loaded.
Can modify the domain object after reading it from a row.



onBeforeConvert(T entity, SqlIdentifier table)

Marks an auditable entity created or modified



onBeforeSave(T entity, OutboundRow row, SqlIdentifier table)

Invoked before a domain object is saved.
Can modify the target, to be persisted, OutboundRow containing all mapped entity information.



onAfterSave(T entity, OutboundRow row, SqlIdentifier table)

Invoked after a domain object is saved.
Can modify the domain object, to be returned after save, OutboundRow containing all mapped entity information.


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:

@EnableR2dbcRepositories(basePackages = "com.acme.mysql", entityOperationsRef = "mysqlR2dbcEntityOperations")
static class MySQLConfiguration {

    public ConnectionFactory mysqlConnectionFactory() {
        return …

    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:

Example 10. Activating auditing using JavaConfig
class Config {

  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 class com.bigbank.SavingsAccount maps to the savings_account table name.

  • 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:

Example 11. @Configuration class to configure R2DBC mapping support
public class MyAppConfig extends AbstractR2dbcConfiguration {

  public ConnectionFactory connectionFactory() {
    return ConnectionFactories.get("r2dbc:…");

  // the following are optional

  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.

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:

Example 12. Example domain object
package com.mycompany.domain;

public class Person {

  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


Can be customized using Explicit Converters.

JSR-310 Date/Time types


Can be customized using Explicit Converters.

String, BigInteger, BigDecimal, and UUID


Can be customized using Explicit Converters.



Can be customized by registering a Explicit Converters.

Blob and Clob


Can be customized using Explicit Converters.

byte[], ByteBuffer


Considered a binary payload.


Array of T

Conversion to Array type if supported by the configured driver, not supported otherwise.

Arrays of primitive types, wrapper types and String

Array of wrapper type (e.g. int[]Integer[])

Conversion to Array type if supported by the configured driver, not supported otherwise.

Driver-specific types


Contributed as simple type be the used R2dbcDialect.

Complex objects

Target type depends on registered Converter.

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 given Row.

  • @Column: Applied at the field level to describe the name of the column as it is represented in the row, allowing the name to be different than the field name of the class.

  • @Version: Applied at field level is used for optimistic locking and checked for modification on save operations. The value is null (zero for primitive types) is considered as marker for entities to be new. The initially stored value is zero (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 for javac 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:

 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:

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 and Criteria.

  • [kotlin.coroutines] extensions for DatabaseClient.

Unresolved directive in reference/kotlin.adoc - include::../../../../../spring-data-commons/src/main/asciidoc/kotlin-coroutines.adoc[leveloffset=+1]


Unresolved directive in index.adoc - include::../../../../spring-data-commons/src/main/asciidoc/repository-query-keywords-reference.adoc[leveloffset=+1] Unresolved directive in index.adoc - include::../../../../spring-data-commons/src/main/asciidoc/repository-query-return-types-reference.adoc[leveloffset=+1] :leveloffset: +1

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.


  • Deprecation of o.s.d.r2dbc.core.DatabaseClient and its support classes ConnectionAccessor, FetchSpec, SqlProvider and a few more. Named parameter support classes such as NamedParameterExpander are encapsulated by Spring R2DBC’s DatabaseClient implementation hence we’re not providing replacements as this was internal API in the first place. Use o.s.r2dbc.core.DatabaseClient and their Spring R2DBC replacements available from org.springframework.r2dbc.core. Entity-based methods (select/insert/update/delete) methods are available through R2dbcEntityTemplate which was introduced with version 1.1.

  • Deprecation of o.s.d.r2dbc.connectionfactory, o.s.d.r2dbc.connectionfactory.init, and o.s.d.r2dbc.connectionfactory.lookup packages. Use Spring R2DBC’s variant which you can find at o.s.r2dbc.connection.

  • Deprecation of o.s.d.r2dbc.convert.ColumnMapRowMapper. Use o.s.r2dbc.core.ColumnMapRowMapper instead.

  • Deprecation of binding support classes o.s.d.r2dbc.dialect.Bindings, BindMarker, BindMarkers, BindMarkersFactory and related types. Use replacements from org.springframework.r2dbc.core.binding.

  • Deprecation of BadSqlGrammarException, UncategorizedR2dbcException and exception translation at o.s.d.r2dbc.support. Spring R2DBC provides a slim exception translation variant without an SPI for now available through o.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 using SettableValue to Parameter

  • Repository factory support requires o.s.r2dbc.core.DatabaseClient instead of o.s.data.r2dbc.core.DatabaseClient.

Dependency Changes

To make use of Spring R2DBC, make sure to include the following dependency:

  • org.springframework:spring-r2dbc