Provide support to increase developer productivity in Java when using Reactive Relational Database Access. Uses familiar Spring concepts such as a DatabaseClient for core API usage and lightweight repository style data access.
Switch branches/tags
Nothing to show
Clone or download

README.adoc

Spring Data R2DBC

The primary goal of the Spring Data project is to make it easier to build Spring-powered applications that use data access technologies. Spring Data R2DBC offers the popular Repository abstraction based on R2DBC.

R2DBC is the abbreviation for Reactive Relational Database Connectivity, an incubator to integrate relational databases using a reactive driver.

The state of R2DBC is incubating to evaluate how an reactive integration could look like. To get started, you need a R2DBC driver first.

This is NOT an ORM

Spring Data R2DBC does not try to be an ORM. Instead it is more of a construction kit for your personal reactive relational data access component that you can define the way you like or need it.

Maven Coordinates

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-r2dbc</artifactId>
    <version>1.0.0.BUILD-SNAPSHOT</version>
</dependency>

DatabaseClient

All functionality is encapsulated in DatabaseClient which is the entry point for applications that wish to integrate with relational databases using reactive drivers:

PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
		.host(…)
		.database(…)
		.username(…)
		.password(…).build());

DatabaseClient databaseClient = DatabaseClient.create(connectionFactory);

The client API provides covers the following features:

  • Execution of generic SQL and consumption of update count/row results.

  • Generic SELECT with paging and ordering.

  • SELECT of mapped objects with paging and ordering.

  • Generic INSERT with parameter binding.

  • INSERT of mapped objects.

  • Parameter binding using the native syntax.

  • Result consumption: Update count, unmapped (Map<String, Object>), mapped to entities, extraction function.

  • Reactive repositories using @Query annotated methods.

  • Transaction Management.

Examples executing generic SQL statements

Mono<Integer> count = databaseClient.execute()
				.sql("INSERT INTO legoset (id, name, manual) VALUES($1, $2, $3)")
				.bind("$1", 42055)
				.bind("$2", "Description")
				.bindNull("$3", Integer.class)
				.fetch()
				.rowsUpdated();

Flux<Map<String, Object>> rows = databaseClient.execute()
				.sql("SELECT id, name, manual FROM legoset")
				.fetch()
				.all();

Flux<Long> result = db.execute()
				.sql("SELECT txid_current();")
				.map((r, md) -> r.get(0, Long.class))
				.all();

Examples selecting data

Flux<Map<String, Object>> rows = databaseClient.select()
				.from("legoset")
				.orderBy(Sort.by(desc("id")))
				.fetch()
				.all();

Flux<LegoSet> rows = databaseClient.select()
				.from("legoset")
				.orderBy(Sort.by(desc("id")))
				.as(LegoSet.class)
				.fetch()
				.all();

Examples inserting data

Flux<Integer> ids = databaseClient.insert()
				.into("legoset")
				.value("id", 42055)
				.value("name", "Description")
				.nullValue("manual", Integer.class)
				.map((r, m) -> r.get("id", Integer.class)
				.all();

Mono<Void> completion = databaseClient.insert()
				.into(LegoSet.class)
				.using(legoSet)
				.then();

Examples using reactive repositories

interface LegoSetRepository extends ReactiveCrudRepository<LegoSet, Integer> {

		@Query("SELECT * FROM legoset WHERE name like $1")
		Flux<LegoSet> findByNameContains(String name);

		@Query("SELECT * FROM legoset WHERE manual = $1")
		Mono<LegoSet> findByManual(int manual);
}

Examples using transaction control

All examples above run with auto-committed transactions. To get group multiple statements within the same transaction or control the transaction yourself, you need to use TransactionalDatabaseClient:

TransactionalDatabaseClient databaseClient = TransactionalDatabaseClient.create(connectionFactory);

TransactionalDatabaseClient allows multiple flavors of transaction management:

  • Participate in ongoing transactions and fall-back to auto-commit mode if there’s no active transaction (default).

  • Group multiple statements in a managed transaction using TransactionalDatabaseClient.inTransaction(…).

  • Application-controlled transaction management using TransactionalDatabaseClient.beginTransaction()/commitTransaction()/rollbackTransaction().

Participating in ongoing transactions does not require changes to your application code. Instead, a managed transaction must be hosted by your application container. Transaction control needs to happen there, as well.

Statement grouping

Flux<Integer> rowsUpdated = databaseClient.inTransaction(db -> {

	return db.execute().sql("INSERT INTO legoset (id, name, manual) VALUES($1, $2, $3)") //
			.bind(0, 42055) //
			.bind(1, "Description") //
			.bindNull("$3", Integer.class) //
			.fetch()
			.rowsUpdated();
});

Application-controlled transaction management

Flux<Long> txId = databaseClient.execute().sql("SELECT txid_current();").exchange()
				.flatMapMany(it -> it.map((r, md) -> r.get(0, Long.class)).all());

Mono<Void> then = databaseClient.enableTransactionSynchronization(databaseClient.beginTransaction() //
				.thenMany(txId)) //
				.then(databaseClient.rollbackTransaction()));
Note
Application-controlled transactions must be enabled with enableTransactionSynchronization(…).

Building from Source

You don’t need to build from source to use Spring Data R2DBC (binaries in repo.spring.io), but if you want to try out the latest and greatest, Spring Data R2DBC can be easily built with the maven wrapper. You also need JDK 1.8.

$ ./mvnw clean install

If you want to build with the regular mvn command, you will need Maven v3.5.0 or above.

Also see CONTRIBUTING.adoc if you wish to submit pull requests, and in particular please fill out the Contributor’s Agreement before your first change.

Contributing to Spring Data R2DBC

Here are some ways for you to get involved in the community:

  • Get involved with the Spring community by helping out on Stackoverflow by responding to questions and joining the debate.

  • Create GitHub tickets for bugs and new features and comment and vote on the ones that you are interested in.

  • Github is for social coding: if you want to write code, we encourage contributions through pull requests from forks of this repository. If you want to contribute code this way, please reference a JIRA ticket as well, covering the specific issue you are addressing.

  • Watch for upcoming articles on Spring by subscribing to spring.io.

Before we accept a non-trivial patch or pull request we will need you to sign the Contributor License Agreement. Signing the contributor’s agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. If you forget to do so, you’ll be reminded when you submit a pull request. Active contributors might be asked to join the core team, and given the ability to merge pull requests.