#175 - Editing pass for the reference docs.

Edited the reference guide, checking for spelling, grammar, usage, punctuation, and corporate voice.
This commit is contained in:
Jay Bryant
2019-09-04 17:03:22 -05:00
committed by Mark Paluch
parent f691b8c7d7
commit a4b7e57bd5
10 changed files with 330 additions and 226 deletions

View File

@@ -14,17 +14,26 @@ NOTE: Copies of this document may be made for your own use and for distribution
toc::[]
// The blank line before each include prevents content from running together in a bad way
// (because an included bit does not have its own blank lines).
include::preface.adoc[]
include::new-features.adoc[leveloffset=+1]
include::{spring-data-commons-docs}/dependencies.adoc[leveloffset=+1]
include::{spring-data-commons-docs}/repositories.adoc[leveloffset=+1]
[[reference]]
= Reference Documentation
include::reference/introduction.adoc[leveloffset=+1]
include::reference/r2dbc.adoc[leveloffset=+1]
include::reference/r2dbc-repositories.adoc[leveloffset=+1]
include::reference/r2dbc-connections.adoc[leveloffset=+1]
include::reference/mapping.adoc[leveloffset=+1]

View File

@@ -22,57 +22,58 @@ Spring Data uses Spring framework's {spring-framework-ref}/core.html[core] funct
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.
The core functionality of the R2DBC support can be used 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 leverage all the features of Spring Data R2DBC, such as the repository support, you need to configure some parts of the library to use Spring.
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, you can refer to the comprehensive documentation that explains the Spring Framework in detail.
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 https://spring.io/docs[home page] for more information.
[[get-started:first-steps:what]]
== What is R2DBC?
https://r2dbc.io[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 for accessing their relational databases.
https://r2dbc.io[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 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 with 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 limited useful.
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.
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.
[[get-started:first-steps:reactive]]
== What is Reactive?
The term, reactive refers to programming models that are built around reacting to change, availability, and processabilitynetwork components reacting to I/O events, UI controllers reacting to mouse events, resources being made available and others.
The term, "`b`", 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 associated with reactive and that is non-blocking back pressure.
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.
https://github.com/reactive-streams/reactive-streams-jvm/blob/v{reactiveStreamsVersion}/README.md#specification[Reactive Streams is a small spec] (also https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Flow.html[adopted in Java 9]) that defines the interaction between asynchronous components with back pressure.
For example, a data repository (acting as {reactiveStreamsJavadoc}/org/reactivestreams/Publisher.html[`Publisher`]) can produce data that an HTTP server (acting as {reactiveStreamsJavadoc}/org/reactivestreams/Subscriber.html`[`Subscriber`]) can then write to the response.
For example, a data repository (acting as a {reactiveStreamsJavadoc}/org/reactivestreams/Publisher.html[`Publisher`]) can produce data that an HTTP server (acting as a {reactiveStreamsJavadoc}/org/reactivestreams/Subscriber.html`[`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.
[[get-started:first-steps:reactive-api]]
== 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 logicsimilar to the Java 8 Stream API but not only for tables.
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.
https://github.com/reactor/reactor[Project Reactor] is the reactive library of choice for Spring Data R2DBC.
It provides the https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html[`Mono`] and https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html[`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 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 via Reactive Streams.
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 you can apply operations on the output, but you need to adapt the output for use with another reactive library.
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.
[[requirements]]
@@ -89,7 +90,7 @@ The Spring Data R2DBC 1.x binaries require:
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, feel free to use one of the following links:
However, if you encounter issues or you need advice, use one of the following links:
[[get-started:help:community]]
Community Forum :: Spring Data on https://stackoverflow.com/questions/tagged/spring-data[Stack Overflow] is a tag for all Spring Data (not just R2DBC) users to share information and help each other.
@@ -101,9 +102,9 @@ Professional Support :: Professional, from-the-source support, with guaranteed r
[[get-started:up-to-date]]
== Following Development
* For information on the Spring Data R2DBC source code repository, nightly builds, and snapshot artifacts, see the Spring Data R2DBC https://projects.spring.io/spring-data-r2dbc/[homepage].
* For information on the Spring Data R2DBC source code repository, nightly builds, and snapshot artifacts, see the Spring Data R2DBC https://projects.spring.io/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 https://stackoverflow.com/questions/tagged/spring-data[Stack Overflow].
* You can help make Spring Data best serve the needs of the Spring community by interacting with developers through the community on https://stackoverflow.com/questions/tagged/spring-data[Stack Overflow].
* If you encounter a bug or want to suggest an improvement, please create a ticket on the Spring Data R2DBC https://github.com/spring-projects/spring-data-r2dbc/issues[issue tracker].

View File

@@ -1,7 +1,7 @@
[[mapping-chapter]]
= Mapping
Rich mapping support is provided by the `MappingR2dbcConverter`. `MappingR2dbcConverter` has a rich metadata model that allows to map domain objects to a data row.
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.
@@ -26,12 +26,12 @@ 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 will be thrown.
If there is more than one non-zero-argument constructor, an exception is thrown.
[[mapping-configuration]]
== Mapping Configuration
Unless explicitly configured, an instance of `MappingR2dbcConverter` is created by default when you create a `DatabaseClient`.
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.
@@ -67,7 +67,7 @@ public class MyAppConfig extends AbstractR2dbcConfiguration {
You can add additional converters to the converter by overriding the `r2dbcCustomConversions` method.
NOTE: `AbstractR2dbcConfiguration` creates a `DatabaseClient` instance and registers it with the container under the name `databaseClient`.
NOTE: `AbstractR2dbcConfiguration` creates a `DatabaseClient` instance and registers it with the container under the name of `databaseClient`.
[[mapping-usage]]
== Metadata-based Mapping
@@ -98,7 +98,7 @@ public class Person {
----
====
IMPORTANT: The `@Id` annotation tells the mapper which property you want to use for the primary key property.
IMPORTANT: The `@Id` annotation tells the mapper which property you want to use as the primary key.
[[mapping-usage-annotations]]
@@ -106,24 +106,28 @@ IMPORTANT: The `@Id` annotation tells the mapper which property you want to use
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 used for identity purpose.
* `@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 will be 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 and described the name of the column as it will be represented in the row thus allowing the name to be different than the fieldname of the class.
The mapping metadata infrastructure is defined in the separate spring-data-commons project that is technology agnostic. Specific subclasses are using in the R2DBC support to support annotation based metadata. Other strategies are also possible to put in place if there is demand.
* `@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).
[[mapping-custom-object-construction]]
=== 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 it's property information is used to select the appropriate constructor parameter to pass the input field value to. This works only if the parameter name information is present in the java `.class` files which can be achieved by compiling the source with debug information or using the `-parameters` command-line switch for javac in Java 8.
* Otherwise a `MappingException` will be thrown indicating that the given constructor parameter could not be bound.
* 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.
====
[source,java]
----
class OrderItem {
@@ -140,24 +144,26 @@ class OrderItem {
// getters/setters ommitted
}
----
====
[[mapping-explicit-converters]]
=== Overriding Mapping with Explicit Converters
When storing and querying your objects, it is convenient to have a `R2dbcConverter` instance handle the mapping of all Java types to `OutboundRow` instances.
However, sometimes you may want the `R2dbcConverter` instances do most of the work but let you selectively handle the conversion for a particular type -- perhaps to optimize performance.
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 <<mapping-configuration, at the beginning of this chapter>> show how to perform the configuration using Java.
You can use the `r2dbcCustomConversions` method in `AbstractR2dbcConfiguration` to configure converters.
The examples <<mapping-configuration, at the beginning of this chapter>> show how to perform the configuration with Java.
NOTE: 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:
====
[source,java]
----
@ReadingConverter
@@ -170,9 +176,11 @@ The following example of a Spring Converter implementation converts from a `Row`
}
}
----
====
The following example converts from a `Person` to a `OutboundRow`:
====
[source,java]
----
@WritingConverter
@@ -187,3 +195,4 @@ public class PersonWriteConverter implements Converter<Person, OutboundRow> {
}
}
----
====

View File

@@ -20,28 +20,29 @@ That is the responsibility of the administrator who sets up the `ConnectionFacto
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.
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``:
To configure a `ConnectionFactory`:
. Obtain a connection with `ConnectionFactory` as you typically obtain an R2DBC
`ConnectionFactory`.
. Provide an R2DBC URL. (See the documentation for your driver
for the correct value.)
. Obtain a connection with `ConnectionFactory` as you typically obtain an R2DBC `ConnectionFactory`.
. 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:
====
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ConnectionFactory factory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
----
====
[[r2dbc.connections.ConnectionFactoryUtils]]
== 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.
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`.
[[r2dbc.connections.SmartConnectionFactory]]
@@ -62,9 +63,9 @@ The proxy wraps that target `ConnectionFactory` to add awareness of Spring-manag
== 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 per data source.
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()`.
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.

View File

@@ -1,22 +1,24 @@
The R2DBC support contains a wide range of features:
R2DBC contains a wide range of features:
* Spring configuration support with Java-based `@Configuration` classes for an R2DBC driver instance.
* `DatabaseClient` helper class that increases productivity when performing common R2DBC operations with integrated object mapping between rows and POJOs.
* 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.
* 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 leverage the rich mapping functionality.
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.
[[r2dbc.getting-started]]
== Getting Started
An easy way to bootstrap setting up a working environment is to create a Spring-based project through https://start.spring.io[start.spring.io].
An easy way to set up a working environment is to create a Spring-based project through https://start.spring.io[start.spring.io].
To do so:
. Add the following to the pom.xml files `dependencies` element:
+
====
[source,xml,subs="+attributes"]
----
<dependencyManagement>
@@ -50,14 +52,20 @@ An easy way to bootstrap setting up a working environment is to create a Spring-
</dependencies>
----
====
. Change the version of Spring in the pom.xml to be
+
====
[source,xml,subs="+attributes"]
----
<spring.framework.version>{springVersion}</spring.framework.version>
----
. Add the following location of the Spring Milestone repository for Maven to your `pom.xml` such that it is at the same level of your `<dependencies/>` element:
====
. 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:
+
====
[source,xml]
----
<repositories>
@@ -68,18 +76,22 @@ An easy way to bootstrap setting up a working environment is to create a Spring-
</repository>
</repositories>
----
====
The repository is also https://repo.spring.io/milestone/org/springframework/data/[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:
====
[source]
----
logging.level.org.springframework.data.r2dbc=DEBUG
----
====
Then you can create a `Person` class to persist:
Then you can, for example, create a `Person` class to persist, as follows:
====
[source,java]
----
package org.spring.r2dbc.example;
@@ -112,9 +124,11 @@ public class Person {
}
}
----
====
Next, you need to create a table structure in your database:
Next, you need to create a table structure in your database, as follows:
====
[source,sql]
----
CREATE TABLE person
@@ -122,9 +136,11 @@ CREATE TABLE person
name VARCHAR(255),
age INT);
----
====
You also need a main application to run:
You also need a main application to run, as follows:
====
[source,java]
----
package org.spring.r2dbc.example;
@@ -167,9 +183,11 @@ public class R2dbcApp {
}
}
----
====
When you run the main program, the preceding examples produce output similar to the following:
====
[source]
----
2018-11-28 10:47:03,893 DEBUG ata.r2dbc.function.DefaultDatabaseClient: 310 - Executing SQL statement [CREATE TABLE person
@@ -180,11 +198,12 @@ When you run the main program, the preceding examples produce output similar to
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, <<r2dbc.datbaseclient,`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 <<mapping-chapter,here>>.).
* You can create an instance of the central helper class in Spring Data R2DBC (<<r2dbc.datbaseclient,`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 <<mapping-chapter,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.
@@ -196,12 +215,12 @@ There is a https://github.com/spring-projects/spring-data-examples[GitHub reposi
[[r2dbc.connecting]]
== 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 using the IoC container. The following example explains Java-based configuration.
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.
[[r2dbc.connectionfactory]]
=== 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 a `io.r2dbc.spi.ConnectionFactory`:
The following example shows an example of using Java-based bean metadata to register an instance of `io.r2dbc.spi.ConnectionFactory`:
.Registering a `io.r2dbc.spi.ConnectionFactory` object using Java-based bean metadata
====
@@ -221,14 +240,14 @@ public class ApplicationConfiguration extends AbstractR2dbcConfiguration {
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-framework-ref}/data-access.html[Spring's DAO support features].
`AbstractR2dbcConfiguration` registers also `DatabaseClient` that is required for database interaction and for Repository implementation.
`AbstractR2dbcConfiguration` also registers `DatabaseClient`, which is required for database interaction and for Repository implementation.
[[r2dbc.drivers]]
=== R2DBC Drivers
Spring Data R2DBC supports drivers by R2DBC's pluggable SPI mechanism. Any driver implementing the R2DBC spec can be used with Spring Data R2DBC.
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 writing the following drivers are available:
As of this writing, the following drivers are available:
* https://github.com/r2dbc/r2dbc-postgresql[Postgres] (`io.r2dbc:r2dbc-postgresql`)
* https://github.com/r2dbc/r2dbc-h2[H2] (`io.r2dbc:r2dbc-h2`)
@@ -236,10 +255,9 @@ As of writing the following drivers are available:
* https://github.com/jasync-sql/jasync-sql[jasync-sql MySQL] (`com.github.jasync-sql:jasync-r2dbc-mysql`)
Spring Data R2DBC reacts to database specifics by inspecting the `ConnectionFactory` and selects the appropriate database dialect accordingly.
You can configure an own {spring-data-r2dbc-javadoc}/api/org/springframework/data/r2dbc/dialect/R2dbcDialect.html[`R2dbcDialect`] if the used driver is not yet known to Spring Data R2DBC.
You can configure your own {spring-data-r2dbc-javadoc}/api/org/springframework/data/r2dbc/dialect/R2dbcDialect.html[`R2dbcDialect`] if the driver you use is not yet known to Spring Data R2DBC.
TIP: Dialects are resolved by {spring-data-r2dbc-javadoc}/org/springframework/data/r2dbc/dialect/DialectResolver.html[`DialectResolver`] from a `ConnectionFactory`, typically by inspecting `ConnectionFactoryMetadata`. +
TIP: Dialects are resolved by {spring-data-r2dbc-javadoc}/org/springframework/data/r2dbc/dialect/DialectResolver.html[`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`. +
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`.

View File

@@ -1,36 +1,42 @@
[[r2dbc.datbaseclient]]
= 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 your application code can make use of executing SQL queries or calling higher-level functionality such as inserting or selecting data.
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).
NOTE: `DatabaseClient` is a young application component providing a minimal set of convenience methods that is likely to be extended through time.
NOTE: `DatabaseClient` is a recently developed application component that provides a minimal set of convenience methods that is likely to be extended through time.
NOTE: Once configured, `DatabaseClient` is thread-safe and can be reused across multiple instances.
Another central feature of `DatabaseClient` is translation of exceptions thrown by R2DBC drivers into Spring's portable Data Access Exception hierarchy. See "`<<r2dbc.exception>>`" for more information.
Another central feature of `DatabaseClient` is the translation of exceptions thrown by R2DBC drivers into Spring's portable Data Access Exception hierarchy. See "`<<r2dbc.exception>>`" for more information.
The next section contains an example of how to work with the `DatabaseClient` in the context of the Spring container.
[[r2dbc.datbaseclient.create]]
== Creating `DatabaseClient`
== Creating a `DatabaseClient` Object
The simplest way to create a `DatabaseClient` is through a static factory method:
The simplest way to create a `DatabaseClient` object is through a static factory method, as follows:
====
[source,java]
----
DatabaseClient.create(ConnectionFactory connectionFactory)
----
====
The above method creates a `DatabaseClient` with default settings.
The preceding method creates a `DatabaseClient` with default settings.
You can also obtain a `Builder` instance via `DatabaseClient.builder()` with further options to customize the client by calling the following methods:
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 "`<<r2dbc.exception>>`" for more information.
* `….dataAccessStrategy(…)`: Strategy how SQL queries are generated and how objects are mapped.
* `….exceptionTranslator(…)`: Supply a specific `R2dbcExceptionTranslator` to customize how R2DBC exceptions are translated into Spring's portable Data Access Exception hierarchy.
See "`<<r2dbc.exception>>`" 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:
====
[source,java]
----
DatabaseClient client1 = DatabaseClient.builder()
@@ -39,6 +45,7 @@ DatabaseClient client1 = DatabaseClient.builder()
DatabaseClient client2 = client1.mutate()
.exceptionTranslator(exceptionTranslatorB).build();
----
====
== Controlling Database Connections
@@ -46,12 +53,13 @@ Spring Data R2DBC obtains a connection to the database through a `ConnectionFact
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` using your R2DBC driver.
`ConnectionFactory` implementations can either return the same connection, different connections or provide connection pooling.
`DatabaseClient` uses `ConnectionFactory` to create and release connections per operation without affinity to a particular connection across multiple operations.
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'd be using H2 as a database, a typical programmatic setup looks something like this:
Assuming you use H2 as a database, a typical programmatic setup looks something like the following listing:
====
[source, java]
----
H2ConnectionConfiguration config = … <1>
@@ -62,6 +70,7 @@ 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.
====
[[r2dbc.exception]]
= Exception Translation
@@ -74,26 +83,31 @@ Implementations can be generic (for example, using SQLState codes) or proprietar
`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 fallback if it is not able to translate an exception.
`R2dbcExceptionSubclassTranslator` uses `SqlStateR2dbcExceptionTranslator` as its fallback if it is not able to translate an exception.
`SqlErrorCodeR2dbcExceptionTranslator` uses specific vendor codes using Spring JDBC's `SQLErrorCodes`.
It is more precise than the SQLState implementation.
`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.
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.
. 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.
. Any custom implementation of the `SQLExceptionTranslator` interface that is provided as the `customSqlExceptionTranslator` property of the `SQLErrorCodes` class.
. Error code matching is applied.
. Use a fallback translator.
NOTE: The `SQLErrorCodesFactory` is used by default to define Error codes and custom exception translations. They are looked up in a file named `sql-error-codes.xml` from 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.
NOTE: 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:
====
[source,java]
----
public class CustomSqlErrorCodeR2dbcExceptionTranslator extends SqlErrorCodeR2dbcExceptionTranslator {
@@ -108,11 +122,13 @@ public class CustomSqlErrorCodeR2dbcExceptionTranslator extends SqlErrorCodeR2db
}
}
----
====
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 builder method `exceptionTranslator`, and you must use this `DatabaseClient` for all of the data access processing where this translator is needed.
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:
====
[source,java]
----
ConnectionFactory connectionFactory = …;
@@ -125,3 +141,4 @@ DatabaseClient client = DatabaseClient.builder()
.exceptionTranslator(exceptionTranslator)
.build();
----
====

View File

@@ -1,12 +1,14 @@
[[r2dbc.datbaseclient.fluent-api]]
= Fluent Data Access API
You have already seen the SQL API of `DatabaseClient` that offers you maximum flexibility to execute 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 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 data types natively supported by the underlying driver.
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.
Let's take a look at a simple query:
Consider the following simple query:
====
[source,java]
@@ -16,11 +18,12 @@ Flux<Person> people = databaseClient.select()
.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.
<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 `ORDER BY` clause:
The following example declares a more complex query that specifies the table name by name, a `WHERE` condition, and an `ORDER BY` clause:
====
[source,java]
@@ -36,75 +39,83 @@ Mono<Person> first = databaseClient.select()
----
<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 just 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.
<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 (e.g. `as(Class<T>)`) using Spring Data's mapping-metadata.
* As `Map<String, Object>` where column names are mapped to their value. Column names are looked up case-insensitive.
* By supplying a mapping `BiFunction` for direct access to R2DBC `Row` and `RowMetadata`
* 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 as through the terminating methods:
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 row then `Mono` completes exceptionally emitting `IncorrectResultSizeDataAccessException`.
* `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. Typically used with `INSERT`/`UPDATE`/`DELETE` statements.
* `rowsUpdated`: Consume the number of affected rows.
It is typically used with `INSERT`,`UPDATE`, and `DELETE` statements.
[[r2dbc.datbaseclient.fluent-api.select]]
== Selecting Data
Use the `select()` entry point to express your `SELECT` queries.
The resulting `SELECT` queries support the commonly used clauses `WHERE`, `ORDER BY` and support pagination.
The fluent API style allows you to chain together multiple methods while having easy-to-understand code.
To improve readability, use static imports that allow you avoid using the 'new' keyword for creating `Criteria` instances.
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.
[r2dbc.datbaseclient.fluent-api.criteria]]
==== 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 using the `>` operator.
* `Criteria` *greaterThanOrEquals* `(Object o)` Creates a criterion using the `>=` operator.
* `Criteria` *in* `(Object... o)` Creates a criterion using the `IN` operator for a varargs argument.
* `Criteria` *in* `(Collection<?> collection)` Creates a criterion using the `IN` operator using a collection.
* `Criteria` *is* `(Object o)` Creates a criterion using column matching (`property = value`).
* `Criteria` *isNull* `()` Creates a criterion using the `IS NULL` operator.
* `Criteria` *isNotNull* `()` Creates a criterion using the `IS NOT NULL` operator.
* `Criteria` *lessThan* `(Object o)` Creates a criterion using the `<` operator.
* `Criteria` *lessThanOrEquals* `(Object o)` Creates a criterion using the `<=` operator.
* `Criteria` *like* `(Object o)` Creates a criterion using the `LIKE` operator without escape character processing.
* `Criteria` *not* `(Object o)` Creates a criterion using the `!=` operator.
* `Criteria` *notIn* `(Object... o)` Creates a criterion using the `NOT IN` operator for a varargs argument.
* `Criteria` *notIn* `(Collection<?> collection)` Creates a criterion using the `NOT IN` operator using a collection.
* `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.
[r2dbc.datbaseclient.fluent-api.select.methods]]
==== Methods for SELECT operations
==== Methods for `SELECT` operations
The `select()` entry point exposes some additional methods that provide options for the query:
* *from* `(Class<T>)` used to specify the source table using a mapped object. Returns results by default as `T`.
* *from* `(String)` used to specify the source table name. Returns results by default as `Map<String, Object>`.
* *as* `(Class<T>)` used to map results to `T`.
* *map* `(BiFunction<Row, RowMetadata, T>)` used to supply a mapping function to extract results.
* *project* `(String... columns)` used to specify which columns to return.
* *matching* `(Criteria)` used to declare a `WHERE` condition to filter results.
* *orderBy* `(Order)` used to declare a `ORDER BY` clause to sort results.
* *page* `(Page pageable)` used to retrieve a particular page within the result. Limits the size of the returned results and reads from a offset.
* *fetch* `()` transition call declaration to the fetch stage to declare result consumption multiplicity.
* *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.
[[r2dbc.datbaseclient.fluent-api.insert]]
== Inserting Data
Use the `insert()` entry point to insert data. Similar to `select()`, `insert()` allows free-form and mapped object inserts.
You can use the `insert()` entry point to insert data. Similar to `select()`, `insert()` allows free-form and mapped object inserts.
Take a look at a simple typed insert operation:
Consider the following simple typed insert operation:
====
[source,java]
@@ -114,12 +125,16 @@ Mono<Void> insert = databaseClient.insert()
.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 these.
<3> Use `then()` to just insert an object without consuming further details. Modifying statements allow consumption of the number of affected rows or tabular results for consuming generated keys.
<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:
Inserts also support untyped operations, as the following example shows:
====
[source,java]
@@ -133,32 +148,36 @@ Mono<Void> insert = databaseClient.insert()
<1> Start an insert into the `person` table.
<2> Provide a non-null value for `firstname`.
<3> Set `lastname` to `null`.
<3> Use `then()` to just insert an object without consuming further details. Modifying statements allow consumption of the number of affected rows or tabular results for consuming generated keys.
<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.
====
[r2dbc.datbaseclient.fluent-api.insert.methods]]
==== Methods for INSERT operations
The `insert()` entry point exposes some additional methods that provide options for the operation:
The `insert()` entry point exposes the following additional methods to provide options for the operation:
* *into* `(Class<T>)` used to specify the target table using a mapped object. Returns results by default as `T`.
* *into* `(String)` used to specify the target table name. Returns results by default as `Map<String, Object>`.
* *using* `(T)` used to specify the object to insert.
* *using* `(Publisher<T>)` used to accept a stream of objects to insert.
* *table* `(String)` used to override the target table name.
* *value* `(String, Object)` used to provide a column value to insert.
* *nullValue* `(String)` used to provide a null value to insert.
* *map* `(BiFunction<Row, RowMetadata, T>)` used to supply a mapping function to extract results.
* *then* `()` execute `INSERT` without consuming any results.
* *fetch* `()` transition call declaration to the fetch stage to declare result consumption multiplicity.
* *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.
[[r2dbc.datbaseclient.fluent-api.update]]
== Updating Data
Use the `update()` entry point to update rows.
Updating data starts with a specification of the table to update accepting `Update` specifying assignments. It also accepts `Criteria` to create a `WHERE` clause.
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.
Take a look at a simple typed update operation:
Consider the following simple typed update operation:
====
[source,java]
@@ -171,11 +190,13 @@ Mono<Void> update = databaseClient.update()
.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 just update rows an object without consuming further details. Modifying statements allow also consumption of the number of affected rows.
<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 support untyped operations:
Update also supports untyped operations, as the following example shows:
====
[source,java]
@@ -186,32 +207,36 @@ Mono<Void> update = databaseClient.update()
.matching(where("firstname").is("John")) <3>
.then(); <4>
----
<1> Update table `person`.
<2> Provide a `Update` definition, which columns to update.
<3> The issued query declares a `WHERE` condition on `firstname` columns to filter rows to update.
<4> Use `then()` to just update rows an object without consuming further details. Modifying statements allow also consumption of the number of affected rows.
<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.
====
[r2dbc.datbaseclient.fluent-api.update.methods]]
==== Methods for UPDATE operations
The `update()` entry point exposes some additional methods that provide options for the operation:
The `update()` entry point exposes the following additional methods to provide options for the operation:
* *table* `(Class<T>)` used to specify the target table using a mapped object. Returns results by default as `T`.
* *table* `(String)` used to specify the target table name. Returns results by default as `Map<String, Object>`.
* *using* `(T)` used to specify the object to update. Derives criteria itself.
* *using* `(Update)` used to specify the update definition.
* *matching* `(Criteria)` used to declare a `WHERE` condition to rows to update.
* *then* `()` execute `UPDATE` without consuming any results.
* *fetch* `()` transition call declaration to the fetch stage to fetch the number of updated rows.
* *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.
[[r2dbc.datbaseclient.fluent-api.delete]]
== Deleting Data
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.
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.
Take a look at a simple insert operation:
Consider the following simple insert operation:
====
[source,java]
@@ -222,18 +247,20 @@ Mono<Void> delete = databaseClient.delete()
.and("lastname").in("Doe", "White"))
.then(); <3>
----
<1> Using `Person` with the `from(…)` method sets the `FROM` table based on mapping metadata.
<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 just delete rows an object without consuming further details. Modifying statements allow also consumption of the number of affected rows.
<3> Use `then()` to delete rows from an object without consuming further details.
Modifying statements also allow consumption of the number of affected rows.
====
[r2dbc.datbaseclient.fluent-api.delete.methods]]
==== Methods for DELETE operations
The `delete()` entry point exposes some additional methods that provide options for the operation:
The `delete()` entry point exposes the following additional methods to provide options for the operation:
* *from* `(Class<T>)` used to specify the target table using a mapped object. Returns results by default as `T`.
* *from* `(String)` used to specify the target table name. Returns results by default as `Map<String, Object>`.
* *matching* `(Criteria)` used to declare a `WHERE` condition to rows to delete.
* *then* `()` execute `DELETE` without consuming any results.
* *fetch* `()` transition call declaration to the fetch stage to fetch the number of deleted rows.
* *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.

View File

@@ -2,8 +2,6 @@
= R2DBC Repositories
[[r2dbc.repositories.intro]]
== Introduction
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,7 +10,8 @@ Before reading this chapter, you should have a sound understanding of the basic
== 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, as the following example shows:
To do so, create an interface for your repository.
Consider the following `Person` class:
.Sample Person entity
====
@@ -30,6 +29,8 @@ public class Person {
----
====
The following example shows a repository interface for the preceding `Person` class:
.Basic repository interface to persist Person entities
====
[source]
@@ -41,7 +42,7 @@ public interface PersonRepository extends ReactiveCrudRepository<Person, Long> {
----
====
Right now, this interface serves only to provide type information, but we can add additional methods to it later.
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:
@@ -63,8 +64,8 @@ class ApplicationConfig extends AbstractR2dbcConfiguration {
====
Because our domain repository extends `ReactiveCrudRepository`, it provides you with CRUD operations to access the entities.
Working with the repository instance is just a matter of dependency injecting it into a client.
Consequently, you can retrieve all `Person` objects would resemble the following code:
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:
.Paging access to Person entities
====
@@ -90,12 +91,12 @@ public class PersonRepositoryTests {
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 test aid to verify our expectations against the results.
We use `StepVerifier` as a test aid to verify our expectations against the results.
[[r2dbc.repositories.queries]]
== Query Methods
Most of the data access operations you usually trigger on a repository result in a query being executed against the databases.
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:
.PersonRepository with query methods
@@ -113,11 +114,11 @@ public interface PersonRepository extends ReactiveCrudRepository<Person, Long> {
}
----
<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.
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.
====
NOTE: R2DBC repositories do not support query derivation.
NOTE: R2DBC repositories bind internally parameters to placeholders via `Statement.bind(…)` by index.
NOTE: R2DBC repositories internally bind parameters to placeholders with `Statement.bind(…)` by index.

View File

@@ -1,18 +1,20 @@
[[r2dbc.datbaseclient.statements]]
= Executing Statements
Running a statement is the basic functionality that is covered by `DatabaseClient`.
`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:
====
[source,java]
----
Mono<Void> completion = client.execute("CREATE TABLE person (id VARCHAR(255) PRIMARY KEY, name VARCHAR(255), age INTEGER);")
.then();
----
====
`DatabaseClient` is designed for a convenient fluent usage.
`DatabaseClient` is designed for convenient, fluent usage.
It exposes intermediate, continuation, and terminal methods at each stage of the execution specification.
The 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.
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.
NOTE: `execute(…)` accepts either the SQL query string or a query `Supplier<String>` to defer the actual query creation until execution.
@@ -24,38 +26,46 @@ SQL queries can return values or the number of affected rows.
The following example shows an `UPDATE` statement that returns the number of updated rows:
====
[source,java]
----
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`.
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 allows you to specify how much data you want to consume.
`fetch()` is a continuation operator that lets you specify how much data you want to consume.
====
[source,java]
----
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
* `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)
* `all()` returns all rows of the result.
* `rowsUpdated()` returns the number of affected rows (`INSERT` count, `UPDATE` count).
`DatabaseClient` queries return their results by default as `Map` of column name to value. You can customize type mapping by applying an `as(Class<T>)` operator.
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:
====
[source,java]
----
Flux<Person> all = client.execute("SELECT id, name FROM mytable")
.as(Person.class)
.fetch().all();
----
====
`as(…)` applies <<mapping-conventions,Convention-based Object Mapping>> and maps the resulting columns to your POJO.
@@ -63,43 +73,47 @@ Flux<Person> all = client.execute("SELECT id, name FROM mytable")
== 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/maps, objects).
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:
====
[source,java]
----
Flux<String> names = client.execute("SELECT name FROM person")
.map((row, rowMetadata) -> row.get("id", String.class))
.all();
----
====
[[r2dbc.datbaseclient.mapping.null]]
.What about `null`?
****
Relational database results may contain `null` values.
Reactive Streams forbids emission of `null` values which requires a proper `null` handling in the extractor function.
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 (e.g. `Optional` for singular values) to make sure a `null` value is never returned directly by your extractor function.
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.
****
[[r2dbc.datbaseclient.binding]]
== 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`/`UPDATE` statements accepting input parameters.
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.
`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 using prepared statements and parameter substitution.
Your R2DBC driver then executes the statement by using prepared statements and parameter substitution.
Parameter binding supports various binding strategies:
Parameter binding supports two binding strategies:
* By Index using zero-based parameter indexes.
* By Name using the placeholder name.
* By Index, using zero-based parameter indexes.
* By Name, using the placeholder name.
The following example shows parameter binding for a query:
====
[source,java]
----
db.execute("INSERT INTO person (id, name, age) VALUES(:id, :name, :age)")
@@ -107,33 +121,37 @@ db.execute("INSERT INTO person (id, name, age) VALUES(:id, :name, :age)")
.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 that uses named bind markers prefixed with `@` (at).
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 `?` (question mark) as bind markers.
In JDBC, the actual drivers translate question mark bind markers to database-native markers as part of their statement execution.
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 allows you to use native bind markers or named bind markers with the `:name` syntax.
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.
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 e.g. select lists.
Nested object arrays are expanded to allow usage of (for example) select lists.
Consider the following query:
====
[source,sql]
----
SELECT id, name, state FROM table WHERE (name, age) IN (('John', 35), ('Ann', 50))
----
====
This query can be parametrized and executed as:
The preceding query can be parametrized and executed as follows:
====
[source,java]
----
List<Object[]> tuples = new ArrayList<>();
@@ -143,13 +161,16 @@ tuples.add(new Object[] {"Ann", 50});
db.execute("SELECT id, name, state FROM table WHERE (name, age) IN (:tuples)")
.bind("tuples", tuples);
----
====
NOTE: Usage of select lists is vendor-dependent.
A simpler variant using `IN` predicates:
The following example shows a simpler variant using `IN` predicates:
====
[source,java]
----
db.execute("SELECT id, name, state FROM table WHERE age IN (:ages)")
.bind("ages", Arrays.asList(35, 50));
----
====

View File

@@ -3,12 +3,13 @@
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.
Using different connections hence results in utilizing different transactions.
Spring Data R2DBC includes transaction-awareness in `DatabaseClient` that allows you to group multiple statements within
the same transaction using {spring-framework-ref}/data-access.html#transaction[Spring's Transaction Management].
Spring Data R2DBC provides a implementation for `ReactiveTransactionManager` with `R2dbcTransactionManager`.
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-framework-ref}/data-access.html#transaction[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
.Programmatic Transaction Management
====
[source,java]
@@ -35,8 +36,7 @@ Mono<Void> atomicOperation = client.execute("INSERT INTO person (id, name, age)
<2> Bind the operation to the `TransactionalOperator`.
====
{spring-framework-ref}/data-access.html#transaction-declarative[Spring's declarative Transaction Management]
is a less invasive, annotation-based approach to transaction demarcation.
{spring-framework-ref}/data-access.html#transaction-declarative[Spring's declarative Transaction Management] is a less invasive, annotation-based approach to transaction demarcation, as the following example shows:
.Declarative Transaction Management
====