Fork me on GitHub

R2DBC Tutorial

This tutorial demonstrates using R2DBC logic within WoOF.

It is a simple application to retrieve data from a database. As such, the configuration for this tutorial is the following:

ReactorHttpServer screen shot.

Tutorial Source

Reactive logic

The following is the R2DBC logic to retrieve the data:

	public Mono<Message> retrieveData(@HttpPathParameter("id") String id, R2dbcSource source) {
		return source.getConnection()
				.flatMap(connection -> Mono.from(connection.createStatement("SELECT CONTENT FROM MESSAGE WHERE ID = $1")
						.bind(0, Integer.parseInt(id)).execute()))
				.flatMap(result -> Mono.from(result.map((row, metadata) -> {
					String content = row.get(0, String.class);
					return new Message(content);
				})));
	}

The R2dbcSource provides access to obtain a connection.

To enable the returned Reator types to be handled natively by OfficeFloor, add the following:

		<dependency>
			<groupId>net.officefloor.reactor</groupId>
			<artifactId>officereactor</artifactId>
		</dependency>

OfficeFloor will subscribe to the returned Mono. The success is passed as parameter to the next procedure (sending it as response):

	public void send(@Parameter Message message, ObjectResponse<Message> response) {
		response.send(message);
	}

R2DBC

To have the R2DBC available, add the following:

		<dependency>
			<groupId>net.officefloor.persistence</groupId>
			<artifactId>officer2dbc</artifactId>
		</dependency>
		
		<!-- Also include appropriate R2DBC libraries for particular database -->
		<dependency>
			<groupId>io.r2dbc</groupId>
			<artifactId>r2dbc-h2</artifactId>
		</dependency>
		<dependency>
			<groupId>io.r2dbc</groupId>
			<artifactId>r2dbc-pool</artifactId>
		</dependency>

then configure as follows in application.objects:

	<managed-object source="net.officefloor.r2dbc.R2dbcManagedObjectSource">
		<property-file path="datasource.properties" />
	</managed-object>

with example properties:

driver=pool
protocol=h2:mem
database=exampleDb
user=sa
password=password

Testing

The following shows invoking the R2DBC code that asynchronously retrieves data:

	@RegisterExtension
	public final MockWoofServerExtension server = new MockWoofServerExtension();

	@Test
	public void getData() {
		MockWoofResponse response = this.server.send(MockWoofServer.mockRequest("/message/1"));
		response.assertJson(200, new Message("TEST"));
	}

Next

The next tutorial covers using Vertx SQL Client.