© 2018-2019 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:

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.0.0 M2

  • Support for named parameters.

9.2. What’s New in Spring Data R2DBC 1.0.0 M1

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

  • A DatabaseClient helper class that increases productivity when performing common R2DBC operations with integrated object mapping between rows and POJOs.

  • Exception translation into Spring’s portable Data Access Exception hierarchy.

  • 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 DatabaseClient or the repository support, which both use the rich mapping functionality. DatabaseClient 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:

    <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.0.0.BUILD-SNAPSHOT</version>
      </dependency>
    
      <!-- a R2DBC driver -->
      <dependency>
        <groupId>io.r2dbc</groupId>
        <artifactId>r2dbc-h2</artifactId>
        <version>Arabba-RC1</version>
      </dependency>
    
    </dependencies>
  2. Change the version of Spring in the pom.xml to be

    <spring.framework.version>5.2.0.RELEASE</spring.framework.version>
  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:

    <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.data.r2dbc=DEBUG

Then you can, for example, create a Person class to persist, as follows:

package org.spring.r2dbc.example;

public class Person {

  private String id;
  private String name;
  private 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:

package org.spring.r2dbc.example;

public class R2dbcApp {

  private static final Log log = LogFactory.getLog(R2dbcApp.class);

  public static void main(String[] args) throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");

    DatabaseClient client = DatabaseClient.create(connectionFactory);

    client.execute("CREATE TABLE person" +
        "(id VARCHAR(255) PRIMARY KEY," +
        "name VARCHAR(255)," +
        "age INT)")
      .fetch()
      .rowsUpdated()
      .as(StepVerifier::create)
      .expectNextCount(1)
      .verifyComplete();

    client.insert()
      .into(Person.class)
      .using(new Person("joe", "Joe", 34))
      .then()
      .as(StepVerifier::create)
      .verifyComplete();

    client.select()
      .from(Person.class)
      .fetch()
      .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 ata.r2dbc.function.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 ata.r2dbc.function.DefaultDatabaseClient: 908 - Executing SQL statement [INSERT INTO person (id, name, age) VALUES($1, $2, $3)]
2018-11-28 10:47:04,092 DEBUG ata.r2dbc.function.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 (DatabaseClient) 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.

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
@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. R2DBC is a relatively young initiative that gains significance by maturing through adoption. As of this writing, the following drivers are available:

Spring Data R2DBC reacts to database specifics by inspecting the ConnectionFactory and selects the appropriate database dialect accordingly. You can 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. Introduction to DatabaseClient

Spring Data R2DBC includes a reactive, non-blocking DatabaseClient for database interaction. The client has a functional, fluent API with reactive types for declarative composition. DatabaseClient encapsulates resource handling (such as opening and closing connections) so that your application code can run SQL queries or call higher-level functionality (such as inserting or selecting data).

DatabaseClient is a recently developed application component that provides a minimal set of convenience methods that is likely to be extended through time.
Once configured, DatabaseClient is thread-safe and can be reused across multiple instances.

Another central feature of DatabaseClient is the translation of exceptions thrown by R2DBC drivers into Spring’s portable Data Access Exception hierarchy. See “Exception Translation” for more information.

The next section contains an example of how to work with the DatabaseClient in the context of the Spring container.

11.4.1. Creating a DatabaseClient Object

The simplest way to create a DatabaseClient object is through a static factory method, as follows:

DatabaseClient.create(ConnectionFactory connectionFactory)

The preceding method creates a DatabaseClient with default settings.

You can also obtain a Builder instance from DatabaseClient.builder(). You can customize the client by calling the following methods:

  • ….exceptionTranslator(…): Supply a specific R2dbcExceptionTranslator to customize how R2DBC exceptions are translated into Spring’s portable Data Access Exception hierarchy. See “Exception Translation” for more information.

  • ….dataAccessStrategy(…): Set the strategy how SQL queries are generated and how objects are mapped.

Once built, a DatabaseClient instance is immutable. However, you can clone it and build a modified copy without affecting the original instance, as the following example shows:

DatabaseClient client1 = DatabaseClient.builder()
  .exceptionTranslator(exceptionTranslatorA).build();

DatabaseClient client2 = client1.mutate()
  .exceptionTranslator(exceptionTranslatorB).build();

11.4.2. Controlling Database Connections

Spring Data R2DBC obtains a connection to the database through a ConnectionFactory. A ConnectionFactory is part of the R2DBC specification and is a generalized connection factory. It lets a container or a framework hide connection pooling and transaction management issues from the application code.

When you use Spring Data R2DBC, you can create a ConnectionFactory by using your R2DBC driver. ConnectionFactory implementations can either return the same connection or different connections or provide connection pooling. DatabaseClient uses ConnectionFactory to create and release connections for each operation without affinity to a particular connection across multiple operations.

Assuming you use H2 as a database, a typical programmatic setup looks something like the following listing:

H2ConnectionConfiguration config = … (1)
ConnectionFactory factory = new H2ConnectionFactory(config); (2)

DatabaseClient client = DatabaseClient.create(factory); (3)
1 Prepare the database specific configuration (host, port, credentials etc.)
2 Create a connection factory using that configuration.
3 Create a DatabaseClient to use that connection factory.

11.5. Exception Translation

The Spring framework provides exception translation for a wide variety of database and mapping technologies. The Spring support for R2DBC extends this feature by providing implementations of the R2dbcExceptionTranslator interface.

R2dbcExceptionTranslator is an interface to be implemented by classes that can translate between R2dbcException and Spring’s own org.springframework.dao.DataAccessException, which is agnostic in regard to data access strategy. Implementations can be generic (for example, using SQLState codes) or proprietary (for example, using Postgres error codes) for greater precision.

R2dbcExceptionSubclassTranslator is the implementation of R2dbcExceptionTranslator that is used by default. It considers R2DBC’s categorized exception hierarchy to translate these into Spring’s consistent exception hierarchy. R2dbcExceptionSubclassTranslator uses SqlStateR2dbcExceptionTranslator as its fallback if it is not able to translate an exception.

SqlErrorCodeR2dbcExceptionTranslator uses specific vendor codes by using Spring JDBC’s SQLErrorCodes. It is more precise than the SQLState implementation. The error code translations are based on codes held in a JavaBean type class called SQLErrorCodes. Instances of this class are created and populated by an SQLErrorCodesFactory, which (as the name suggests) is a factory for creating SQLErrorCodes based on the contents of a configuration file named sql-error-codes.xml from Spring’s Data Access module. This file is populated with vendor codes and based on the ConnectionFactoryName taken from ConnectionFactoryMetadata. The codes for the actual database you are using are used.

The SqlErrorCodeR2dbcExceptionTranslator applies matching rules in the following sequence:

  1. Any custom translation implemented by a subclass. Normally, the provided concrete SqlErrorCodeR2dbcExceptionTranslator is used, so this rule does not apply. It applies only if you have actually provided a subclass implementation.

  2. Any custom implementation of the SQLExceptionTranslator interface that is provided as the customSqlExceptionTranslator property of the SQLErrorCodes class.

  3. Error code matching is applied.

  4. Use a fallback translator.

By default, the SQLErrorCodesFactory is used to define error codes and custom exception translations. They are looked up from a file named sql-error-codes.xml (which must be on the classpath), and the matching SQLErrorCodes instance is located based on the database name from the database metadata of the database in use. SQLErrorCodesFactory requires Spring JDBC.

You can extend SqlErrorCodeR2dbcExceptionTranslator, as the following example shows:

public class CustomSqlErrorCodeR2dbcExceptionTranslator extends SqlErrorCodeR2dbcExceptionTranslator {

  protected DataAccessException customTranslate(String task, String sql, R2dbcException r2dbcex) {

    if (sqlex.getErrorCode() == -12345) {
      return new DeadlockLoserDataAccessException(task, r2dbcex);
    }

    return null;
  }
}

In the preceding example, the specific error code (-12345) is translated, while other errors are left to be translated by the default translator implementation. To use this custom translator, you must configure DatabaseClient through the exceptionTranslator builder method, and you must use this DatabaseClient for all of the data access processing where this translator is needed. The following example shows how you can use this custom translator:

ConnectionFactory connectionFactory = …;

CustomSqlErrorCodeR2dbcExceptionTranslator exceptionTranslator =
  new CustomSqlErrorCodeR2dbcExceptionTranslator();

DatabaseClient client = DatabaseClient.builder()
  .connectionFactory(connectionFactory)
  .exceptionTranslator(exceptionTranslator)
  .build();

11.6. Executing Statements

DatabaseClient provides the basic functionality of running a statement. The following example shows what you need to include for minimal but fully functional code that creates a new table:

Mono<Void> completion = client.execute("CREATE TABLE person (id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), age INTEGER);")
        .then();

DatabaseClient is designed for convenient, fluent usage. It exposes intermediate, continuation, and terminal methods at each stage of the execution specification. The preceding example above uses then() to return a completion Publisher that completes as soon as the query (or queries, if the SQL query contains multiple statements) completes.

execute(…) accepts either the SQL query string or a query Supplier<String> to defer the actual query creation until execution.

11.6.1. Running Queries

SQL queries can return values or the number of affected rows. DatabaseClient can return the number of updated rows or the rows themselves, depending on the issued query.

The following example shows an UPDATE statement that returns the number of updated rows:

Mono<Integer> affectedRows = client.execute("UPDATE person SET name = 'Joe'")
        .fetch().rowsUpdated();

Running a SELECT query returns a different type of result, in particular tabular results. Tabular data is typically consumed by streaming each Row. You might have noticed the use of fetch() in the previous example. fetch() is a continuation operator that lets you specify how much data you want to consume.

Mono<Map<String, Object>> first = client.execute("SELECT id, name FROM person")
        .fetch().first();

Calling first() returns the first row from the result and discards remaining rows. You can consume data with the following operators:

  • first() return the first row of the entire result.

  • one() returns exactly one result and fails if the result contains more rows.

  • all() returns all rows of the result.

  • rowsUpdated() returns the number of affected rows (INSERT count, UPDATE count).

By default, DatabaseClient queries return their results as Map of column name to value. You can customize type mapping by applying an as(Class<T>) operator, as follows:

Flux<Person> all = client.execute("SELECT id, name FROM mytable")
        .as(Person.class)
        .fetch().all();

as(…) applies Convention-based Object Mapping and maps the resulting columns to your POJO.

11.6.2. Mapping Results

You can customize result extraction beyond Map and POJO result extraction by providing an extractor BiFunction<Row, RowMetadata, T>. The extractor function interacts directly with R2DBC’s Row and RowMetadata objects and can return arbitrary values (singular values, collections and maps, and objects).

The following example extracts the id column and emits its value:

Flux<String> names = client.execute("SELECT name FROM person")
        .map((row, rowMetadata) -> row.get("id", String.class))
        .all();
What about null?

Relational database results can contain null values. The Reactive Streams specification forbids the emission of null values. That requirement mandates proper null handling in the extractor function. While you can obtain null values from a Row, you must not emit a null value. You must wrap any null values in an object (for example, Optional for singular values) to make sure a null value is never returned directly by your extractor function.

11.6.3. Binding Values to Queries

A typical application requires parameterized SQL statements to select or update rows according to some input. These are typically SELECT statements constrained by a WHERE clause or INSERT and UPDATE statements that accept input parameters. Parameterized statements bear the risk of SQL injection if parameters are not escaped properly. DatabaseClient leverages R2DBC’s bind API to eliminate the risk of SQL injection for query parameters. You can provide a parameterized SQL statement with the execute(…) operator and bind parameters to the actual Statement. Your R2DBC driver then executes the statement by using prepared statements and parameter substitution.

Parameter binding supports two binding strategies:

  • By Index, using zero-based parameter indexes.

  • By Name, using the placeholder name.

The following example shows parameter binding for a query:

db.execute("INSERT INTO person (id, name, age) VALUES(:id, :name, :age)")
    .bind("id", "joe")
    .bind("name", "Joe")
    .bind("age", 34);
R2DBC Native Bind Markers

R2DBC uses database-native bind markers that depend on the actual database vendor. As an example, Postgres uses indexed markers, such as $1, $2, $n. Another example is SQL Server, which uses named bind markers prefixed with @.

This is different from JDBC, which requires ? as bind markers. In JDBC, the actual drivers translate ? bind markers to database-native markers as part of their statement execution.

Spring Data R2DBC lets you use native bind markers or named bind markers with the :name syntax.

Named parameter support leverages a R2dbcDialect instance to expand named parameters to native bind markers at the time of query execution, which gives you a certain degree of query portability across various database vendors.

The query-preprocessor unrolls named Collection parameters into a series of bind markers to remove the need of dynamic query creation based on the number of arguments. Nested object arrays are expanded to allow usage of (for example) select lists.

Consider the following query:

SELECT id, name, state FROM table WHERE (name, age) IN (('John', 35), ('Ann', 50))

The preceding query can be parametrized and executed as follows:

List<Object[]> tuples = new ArrayList<>();
tuples.add(new Object[] {"John", 35});
tuples.add(new Object[] {"Ann",  50});

db.execute("SELECT id, name, state FROM table WHERE (name, age) IN (:tuples)")
    .bind("tuples", tuples);
Usage of select lists is vendor-dependent.

The following example shows a simpler variant using IN predicates:

db.execute("SELECT id, name, state FROM table WHERE age IN (:ages)")
    .bind("ages", Arrays.asList(35, 50));

11.7. Fluent Data Access API

The SQL API of DatabaseClient offers you maximum flexibility to run any type of SQL. DatabaseClient provides a more narrow 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.

Consider the following simple query:

Flux<Person> people = databaseClient.select()
  .from(Person.class)                         (1)
  .fetch()
  .all();                                     (2)
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 = databaseClient.select()
  .from("legoset")                           (1)
  .matching(where("firstname").is("John")    (2)
    .and("lastname").in("Doe", "White"))
  .orderBy(desc("id"))                       (3)
  .as(Person.class)
  .fetch()
  .one();                                    (4)
1 Selecting from a table by name returns row results as Map<String, Object> with case-insensitive column name matching.
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 consume Query results in three ways:

  • Through object mapping (for example, as(Class<T>)) by using Spring Data’s mapping-metadata.

  • As Map<String, Object> where column names are mapped to their value. Column names are looked up in a case-insensitive way.

  • By supplying a mapping BiFunction for direct access to R2DBC Row and RowMetadata.

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.

  • rowsUpdated: Consume the number of affected rows. It is typically used with INSERT,UPDATE, and DELETE statements.

11.7.1. Selecting Data

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.

Methods for SELECT operations

The select() entry point exposes some additional methods that provide options for the query:

  • from (Class<T>): Specifies the source table by using a mapped object. By default, it returns results as T.

  • from (String): Specifies the source table name. By default, it returns results as Map<String, Object>.

  • as (Class<T>): Maps results to T.

  • map (BiFunction<Row, RowMetadata, T>): Supplies a mapping function to extract results.

  • project (String…​ columns): Specifies which columns to return.

  • matching (Criteria): Declares a WHERE condition to filter results.

  • orderBy (Order): Declares an ORDER BY clause to sort results.

  • page (Page pageable): Retrieves a particular page within the result. It limits the size of the returned results and reads from an offset.

  • fetch (): Transition call declaration to the fetch stage to declare result consumption multiplicity.

11.7.2. Inserting Data

You can use the insert() entry point to insert data. Similar to select(), insert() allows free-form and mapped object inserts.

Consider the following simple typed insert operation:

Mono<Void> insert = databaseClient.insert()
        .into(Person.class)                       (1)
        .using(new Person(…))                     (2)
        .then();                                  (3)
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 execute a stream of INSERT statements. This method extracts all non-null values and inserts them.
3 Use then() to insert an object without consuming further details. Modifying statements allow consumption of the number of affected rows or tabular results for consuming generated keys.

Inserts also support untyped operations, as the following example shows:

Mono<Void> insert = databaseClient.insert()
        .into("person")                           (1)
        .value("firstname", "John")               (2)
        .nullValue("lastname")                    (3)
        .then();                                  (4)
1 Start an insert into the person table.
2 Provide a non-null value for firstname.
3 Set lastname to null.
4 Use then() to insert an object without consuming further details. Modifying statements allow consumption of the number of affected rows or tabular results for consuming generated keys.
Methods for INSERT operations

The insert() entry point exposes the following additional methods to provide options for the operation:

  • into (Class<T>): Specifies the target table using a mapped object. By default, it returns results as T.

  • into (String): Specifies the target table name. By default, it returns results as Map<String, Object>.

  • using (T): Specifies the object to insert.

  • using (Publisher<T>): Accepts a stream of objects to insert.

  • table (String): Overrides the target table name.

  • value (String, Object): Provides a column value to insert.

  • nullValue (String): Provides a null value to insert.

  • map (BiFunction<Row, RowMetadata, T>): Supplies a mapping function to extract results.

  • then (): Executes INSERT without consuming any results.

  • fetch (): Transition call declaration to the fetch stage to declare result consumption multiplicity.

11.7.3. 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 Criteria to create a WHERE clause.

Consider the following simple typed update operation:

Person modified = …

Mono<Void> update = databaseClient.update()
  .table(Person.class)                      (1)
  .using(modified)                          (2)
  .then();                                  (3)
1 Using Person with the table(…) method sets the table to update based on mapping metadata.
2 Provide a scalar Person object value. using(…) accepts the modified object and derives primary keys and updates all column values.
3 Use then() to update the rows of an object without consuming further details. Modifying statements also allow consumption of the number of affected rows.

Update also supports untyped operations, as the following example shows:

Mono<Void> update = databaseClient.update()
  .table("person")                           (1)
  .using(Update.update("firstname", "Jane")) (2)
  .matching(where("firstname").is("John"))   (3)
  .then();                                   (4)
1 Update the person table.
2 Provide a, Update definition of which columns to update.
3 The issued query declares a WHERE condition on firstname columns to filter the rows to update.
4 Use then() to update the rows of an object without consuming further details. Modifying statements also allow consumption of the number of affected rows.
Methods for UPDATE operations

The update() entry point exposes the following additional methods to provide options for the operation:

  • table (Class<T>): Specifies the target table byusing a mapped object. Returns results by default as T.

  • table (String): Specifies the target table name. By default, it returns results as Map<String, Object>.

  • using `(T)`Specifies the object to update. It derives criteria itself.

  • using (Update): Specifies the update definition.

  • matching (Criteria): Declares a WHERE condition to indicate which rows to update.

  • then (): Runs the UPDATE without consuming any results.

  • fetch (): Transition call declaration to the fetch stage to fetch the number of updated rows.

11.7.4. 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<Void> delete = databaseClient.delete()
  .from(Person.class)                       (1)
  .matching(where("firstname").is("John")   (2)
    .and("lastname").in("Doe", "White"))
  .then();                                  (3)
1 Using Person with the from(…) method sets the FROM table, based on mapping metadata.
2 The issued query declares a WHERE condition on firstname and lastname columns to filter rows to delete.
3 Use then() to delete rows from an object without consuming further details. Modifying statements also allow consumption of the number of affected rows.
Methods for DELETE operations

The delete() entry point exposes the following additional methods to provide options for the operation:

  • from (Class<T>): Specifies the target table by using a mapped object. By default, it returns results as T.

  • from (String): Specifies the target table name. By default, it returns results as Map<String, Object>.

  • matching (Criteria): Declares a WHERE condition to define the rows to delete.

  • then (): Runs the DELETE without consuming any results.

  • fetch (): Transition call declaration to the fetch stage to fetch the number of deleted rows.

11.8. Transactions

A common pattern when using relational databases is grouping multiple queries within a unit of work that is guarded by a transaction. Relational databases typically associate a transaction with a single transport connection. Consequently, using different connections results in using different transactions. Spring Data R2DBC includes transaction-awareness in DatabaseClient that lets you group multiple statements within the same transaction by using Spring’s Transaction Management. Spring Data R2DBC provides an implementation for ReactiveTransactionManager with R2dbcTransactionManager. See [r2dbc.connections.R2dbcTransactionManager] for further details.

The following example shows how to programmatically manage a transaction

Example 2. Programmatic Transaction Management
ReactiveTransactionManager tm = new R2dbcTransactionManager(connectionFactory);
TransactionalOperator operator = TransactionalOperator.create(tm); (1)

DatabaseClient client = DatabaseClient.create(connectionFactory);

Mono<Void> atomicOperation = client.execute("INSERT INTO person (id, name, age) VALUES(:id, :name, :age)")
  .bind("id", "joe")
  .bind("name", "Joe")
  .bind("age", 34)
  .fetch().rowsUpdated()
  .then(client.execute("INSERT INTO contacts (id, name) VALUES(:id, :name)")
    .bind("id", "joe")
    .bind("name", "Joe")
    .fetch().rowsUpdated())
  .then()
  .as(operator::transactional); (2)
});
1 Associate the TransactionalOperator with the ReactiveTransactionManager.
2 Bind the operation to the TransactionalOperator.

Spring’s declarative Transaction Management is a less invasive, annotation-based approach to transaction demarcation, as the following example shows:

Example 3. Declarative Transaction Management
@Configuration
@EnableTransactionManagement                                                           (1)
class Config extends AbstractR2dbcConfiguration {

  @Override
  public ConnectionFactory connectionFactory() {
    return // ...
  }

  @Bean
  ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) { (2)
    return new R2dbcTransactionManager(connectionFactory);
  }
}

@Service
class MyService {

  private final DatabaseClient client;

  MyService(DatabaseClient client) {
    this.client = client;
  }

  @Transactional
  public Mono<Void> insertPerson() {

    return client.execute("INSERT INTO person (id, name, age) VALUES(:id, :name, :age)")
      .bind("id", "joe")
      .bind("name", "Joe")
      .bind("age", 34)
      .fetch().rowsUpdated()
      .then(client.execute("INSERT INTO contacts (id, name) VALUES(:id, :name)")
        .bind("id", "joe")
        .bind("name", "Joe")
        .fetch().rowsUpdated())
      .then();
  }
}
1 Enable declarative transaction management.
2 Provide a ReactiveTransactionManager implementation to back reactive transaction features.

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 {

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

Example 5. Basic repository interface to persist Person entities
public interface PersonRepository extends ReactiveCrudRepository<Person, Long> {

  // additional custom query methods go here
}

Right now, this interface provides only type information, but we can add additional methods to it later. 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
@Configuration
@EnableR2dbcRepositories
class ApplicationConfig extends AbstractR2dbcConfiguration {

  @Override
  public ConnectionFactory connectionFactory() {
    return …;
  }
}

Because our domain repository extends ReactiveCrudRepository, it provides you with CRUD operations to access the entities. 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
@RunWith(SpringRunner.class)
@ContextConfiguration
public class PersonRepositoryTests {

  @Autowired PersonRepository repository;

  @Test
  public void readsAllEntitiesCorrectly() {

    repository.findAll()
      .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:

Example 8. PersonRepository with query methods
public interface PersonRepository extends ReactiveCrudRepository<Person, Long> {

  @Query("SELECT * FROM person WHERE lastname = :lastname")
  Flux<Person> findByLastname(String lastname);                      (1)

  @Query("SELECT firstname, lastname FROM person WHERE lastname = $1")
  Mono<Person> findFirstByLastname(String lastname)                  (2)

}
1 The findByLastname method shows a query for all people with the given last name. The query is provided, as R2DBC repositories do not support query derivation.
2 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.
R2DBC repositories do not support query derivation.
R2DBC repositories internally bind parameters to placeholders with Statement.bind(…) by index.

13. Controlling Database Connections

This section covers:

13.1. Using ConnectionFactory

Spring obtains an R2DBC connection to the database through a ConnectionFactory. A ConnectionFactory is part of the R2DBC specification and is a generalized connection factory. It lets a container or a framework hide connection pooling and transaction management issues from the application code. As a developer, you need not know details about how to connect to the database. That is the responsibility of the administrator who sets up the ConnectionFactory. You most likely fill both roles as you develop and test code, but you do not necessarily have to know how the production data source is configured.

When you use Spring’s R2DBC layer, you can can configure your own with a connection pool implementation provided by a third party. A popular implementation is R2DBC Pool. Implementations in the Spring distribution are meant only for testing purposes and do not provide pooling.

To configure a ConnectionFactory:

  1. Obtain a connection with ConnectionFactory as you typically obtain an R2DBC ConnectionFactory.

  2. Provide an R2DBC URL. (See the documentation for your driver for the correct value.)

The following example shows how to configure a ConnectionFactory in Java:

ConnectionFactory factory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");

13.2. Using ConnectionFactoryUtils

The ConnectionFactoryUtils class is a convenient and powerful helper class that provides static methods to obtain connections from ConnectionFactory and close connections (if necessary). It supports subscriber Context-bound connections with, for example ConnectionFactoryTransactionManager.

13.3. Implementing SmartConnectionFactory

The SmartConnectionFactory interface should be implemented by classes that can provide a connection to a relational database. It extends the ConnectionFactory interface to let classes that use it query whether the connection should be closed after a given operation. This usage is efficient when you know that you need to reuse a connection.

13.4. Using TransactionAwareConnectionFactoryProxy

TransactionAwareConnectionFactoryProxy is a proxy for a target ConnectionFactory. The proxy wraps that target ConnectionFactory to add awareness of Spring-managed transactions.

13.5. Using ConnectionFactoryTransactionManager

The ConnectionFactoryTransactionManager class is a ReactiveTransactionManager implementation for single R2DBC datasources. It binds an R2DBC connection from the specified data source to the subscriber Context, potentially allowing for one subscriber connection for each data source.

Application code is required to retrieve the R2DBC connection through ConnectionFactoryUtils.getConnection(ConnectionFactory), instead of R2DBC’s standard ConnectionFactory.create(). All framework classes (such as DatabaseClient) use this strategy implicitly. If not used with this transaction manager, the lookup strategy behaves exactly like the common one. Thus, it can be used in any case.

The ConnectionFactoryTransactionManager class supports custom isolation levels that get applied to the connection.

14. Initializing a ConnectionFactory

The org.springframework.data.r2dbc.connectionfactory.init package provides support for initializing an existing ConnectionFactory. You may sometimes need to initialize an instance that runs on a server somewhere or an embedded database.

14.1. Initializing a Database by Using @Bean methods

If you want to initialize a database and you can provide a reference to a ConnectionFactory bean, you can use the

Example 9. Using ConnectionFactoryInitializer to initialize a ConnectionFactory
@Configuration
public class InitializerConfiguration {

	@Bean
	public ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {

		ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
		initializer.setConnectionFactory(connectionFactory);

		CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
		populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("com/foo/sql/db-schema.sql")));
		populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("com/foo/sql/test-data1.sql")));
		initializer.setDatabasePopulator(populator);

		return initializer;
	}
}

The preceding example runs the two specified scripts against the database. The first script creates a schema, and the second populates tables with a test data set.

The default behavior of the database initializer is to unconditionally run the provided scripts. This may not always be what you want — for instance, if you run the scripts against a database that already has test data in it. The likelihood of accidentally deleting data is reduced by following the common pattern (shown earlier) of creating the tables first and then inserting the data. The first step fails if the tables already exist.

However, to gain more control over the creation and deletion of existing data, ConnectionFactoryInitializer and ResourceDatabasePopulator support various switches such as switching the initialization on and off.

Each statement should be separated by ; or a new line if the ; character is not present at all in the script. You can control that globally or script by script, as the following example shows:

Example 10. Customizing statement separators
@Configuration
public class InitializerConfiguration {

	@Bean
	public ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {

		ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();

		initializer.setConnectionFactory(connectionFactory);

		ResourceDatabasePopulator populator = new ResourceDatabasePopulator(new ClassPathResource("com/foo/sql/db-schema.sql"));
		populator.setSeparator("@@");                                                (1)
		initializer.setDatabasePopulator(populator);

		return initializer;
	}
}
1 Set the separator scripts to @@.

In this example, the schema scripts uses @@ as statement separator.

14.1.1. Initialization of Other Components that Depend on the Database

A large class of applications (those that do not use the database until after the Spring context has started) can use the database initializer with no further complications. If your application is not one of those, you might need to read the rest of this section.

The database initializer depends on a ConnectionFactory instance and runs the scripts provided in its initialization callback (analogous to an init-method in an XML bean definition, a @PostConstruct method in a component, or the afterPropertiesSet() method in a component that implements InitializingBean). If other beans depend on the same data source and use the data source in an initialization callback, there might be a problem because the data has not yet been initialized. A common example of this is a cache that initializes eagerly and loads data from the database on application startup.

To get around this issue, you have two options:

  1. change your cache initialization strategy to a later phase or

  2. ensure that the database initializer is initialized first

Changing your cache initialization strategy might be easy if the application is in your control and not otherwise. Some suggestions for how to implement this include:

  • Make the cache initialize lazily on first usage, which improves application startup time.

  • Have your cache or a separate component that initializes the cache implement Lifecycle or SmartLifecycle. When the application context starts, you can automatically start a SmartLifecycle by setting its autoStartup flag, and you can manually start a Lifecycle by calling ConfigurableApplicationContext.start() on the enclosing context.

  • Use a Spring ApplicationEvent or similar custom observer mechanism to trigger the cache initialization. ContextRefreshedEvent is always published by the context when it is ready for use (after all beans have been initialized), so that is often a useful hook (this is how the SmartLifecycle works by default).

Ensuring that the database initializer is initialized first can also be easy. Some suggestions on how to implement this include:

  • Rely on the default behavior of the Spring BeanFactory, which is that beans are initialized in registration order. You can easily arrange that by adopting the common practice of a set of @Import configuration that order your application modules and ensuring that the database and database initialization are listed first.

  • Separate the ConnectionFactory and the business components that use it and control their startup order by putting them in separate ApplicationContext instances (for example, the parent context contains the ConnectionFactory, and the child context contains the business components).

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

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

15.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
@Configuration
public class MyAppConfig extends AbstractR2dbcConfiguration {

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

  // the following are optional

  @Bean
  @Override
  public R2dbcCustomConversions r2dbcCustomConversions() {

    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 new R2dbcCustomConversions(getStoreConversions(), 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.

15.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;

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

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

String, BigInteger, BigDecimal, and UUID

Passthru

Can be customized using Explicit Converters.

Blob and Clob

Passthru

Can be customized using Explicit Converters.

byte[], ByteBuffer

Passthru

Considered a binary payload.

Collection<T>

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.

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.

15.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 private fields are mapped to the row. This annotation excludes the field where it is applied from being stored in the database

  • @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 key values in the retrieved 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.

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

15.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 String id;
  private int quantity;
  private double unitPrice;

  OrderItem(String id, int quantity, double unitPrice) {
    this.id = id;
    this.quantity = quantity;
    this.unitPrice = unitPrice;
  }

  // getters/setters ommitted
}

15.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;
  }
}

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;
  }
}

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]