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
:
-
Obtain a connection with
ConnectionFactory
as you typically obtain an R2DBCConnectionFactory
. -
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");
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
.
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.
TransactionAwareConnectionFactoryProxy
is a proxy for a target ConnectionFactory
.
The proxy wraps that target ConnectionFactory
to add awareness of Spring-managed transactions.
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.