Introduction to R2dbc

R2dbc drivers

<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-h2</artifactId>
</dependency>
<dependency>
<groupId>dev.miku</groupId>
<artifactId>r2dbc-mysql</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-postgresql</artifactId>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-mssql</artifactId>
</dependency>

Connecting to Databases

ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE")
ConnectionFactories.get("r2dbc:postgres://user:password@localhost/test");
var options = ConnectionFactoryOptions.builder()
.option(ConnectionFactoryOptions.HOST, "localhost")
.option(ConnectionFactoryOptions.DATABASE, "test")
.option(ConnectionFactoryOptions.USER, "user")
.option(ConnectionFactoryOptions.PASSWORD, "password")
.option(ConnectionFactoryOptions.DRIVER, "postgresql")
//.option(PostgresqlConnectionFactoryProvider.OPTIONS, Map.of("lock_timeout", "30s"))
.build();
return ConnectionFactories.get(options);
H2ConnectionFactory.inMemory("test");//file
new H2ConnectionFactory(
H2ConnectionConfiguration.builder()
//.inMemory("testdb")
.file("./testdb")
.username("sa")
.password("password")
.build()
)
new PostgresqlConnectionFactory(
PostgresqlConnectionConfiguration.builder()
.host("localhost")
.database("test")
.username("user")
.password("password")
//.codecRegistrar(EnumCodec.builder().withEnum("post_status", Post.Status.class).build())
.build()
);

Executing SQL queries

String createSql = """
CREATE TABLE IF NOT EXISTS persons (
id SERIAL PRIMARY KEY,
first_name VARCHAR(255),
last_name VARCHAR(255),
age INTEGER
)
""";
String insertSql = """
INSERT INTO persons(first_name, last_name, age)
VALUES
('Hello', 'Kitty', 20),
('Hantsy', 'Bai', 40)
""";

Mono.from(conn)
.flatMap(
c -> Mono.from(c.createStatement(createSql).execute())
)
.log()
.doOnNext(data -> log.info("created: {}", data))
.then()
.thenMany(
Mono.from(conn)
.flatMapMany(
c -> c.createStatement(insertSql)
.returnGeneratedValues("id")
.execute()
)
)
.flatMap(data -> Flux.from(data.map((row, rowMetadata) -> row.get("id"))))
.doOnNext(id -> log.info("generated id: {}", id))
var selectSql = """
SELECT * FROM persons;
""";

Mono.from(conn)
.flatMapMany(
c -> Flux.from(c.createStatement(selectSql).execute())
)
.log()
.flatMap(result -> result
.map((row, rowMetadata) -> {
rowMetadata.getColumnMetadatas()
.forEach(
columnMetadata -> log.info("column name:{}, type: {}", columnMetadata.getName(), columnMetadata.getJavaType())
);

var id = row.get("id", Integer.class);
var firstName = row.get("first_name", String.class);
var lastName = row.get("last_name", String.class);
var age = row.get("age", Integer.class);
return Person.builder().firstName(firstName)
.lastName(lastName)
.age(age)
.id(id)
.build();
}))
.doOnNext(data -> log.info(": {}", data))
var selectSql = """
SELECT * FROM persons WHERE first_name=$1
""";

Mono.from(conn)
.flatMapMany(
c -> Flux.from(c.createStatement(selectSql)
.bind("$1", "Hantsy")
.execute())
)
var updateSql = """
UPDATE persons SET first_name=$1 WHERE first_name=$2
""";
Mono.from(conn)
.flatMapMany(
c -> Flux.from(c.createStatement(updateSql)
.bind("$1", "test1")
.bind("$2", "Hantsy")
.execute())
.flatMap(result -> result.getRowsUpdated())
.doOnNext(data -> log.info(": {}", data))
)
.log()

R2dbc Clients

--

--

--

Self-employed technical consultant, solution architect and full-stack developer, open source contributor, freelancer and remote worker

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

【New Coin Listing】- YesCrypto Token (YCT)

Cat Racing, or: How to Handle Requests Life Cycle in Elm — Part I

Take The Headless Approach: Choose A Frontend Ecommerce Solution

Frontend Ecommerce Solution

How to easily use Apex Replay Debugger with just a few clicks in any Salesforce org

Running MongoDB on Android

Uranium CTF Writeup

Update Aptos on 01.04.2022

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hantsy

Hantsy

Self-employed technical consultant, solution architect and full-stack developer, open source contributor, freelancer and remote worker

More from Medium

Develop REST apis with OpenApi Spec and using custom generators via templates

How to Check the Health of a Spring boot Application using Spring Actuator

Spring Boot with Jooq and Liquibase

Writing REST API with OpenAPI and SpringBoot