Coder Social home page Coder Social logo

sadnessofatlantis / spring-data-r2dbc Goto Github PK

View Code? Open in Web Editor NEW

This project forked from spring-projects/spring-data-r2dbc

0.0 1.0 0.0 869 KB

Provide support to increase developer productivity in Java when using Reactive Relational Database Connectivity. Uses familiar Spring concepts such as a DatabaseClient for core API usage and lightweight repository style data access.

Java 98.02% Kotlin 1.83% TSQL 0.15%

spring-data-r2dbc's Introduction

Spring Data R2DBC

Spring Data R2DBC

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.

Running CI tasks locally

Since this pipeline is purely Docker-based, it’s easy to:

  • Debug what went wrong on your local machine.

  • Test out a a tweak to your test.sh script before sending it out.

  • Experiment against a new image before submitting your pull request.

All of these use cases are great reasons to essentially run what the CI server does on your local machine.

Important
To do this you must have Docker installed on your machine.
  1. docker run -it --mount type=bind,source="$(pwd)",target=/spring-data-r2dbc-github -v /usr/bin/docker:/usr/bin/docker -v /var/run/docker.sock:/var/run/docker.sock adoptopenjdk/openjdk8:latest /bin/bash

    This will launch the Docker image and mount your source code at spring-data-r2dbc-github.

  2. cd spring-data-r2dbc-github

    Next, test everything from inside the container:

  3. ./mvnw -Pci,all-dbs clean dependency:list test -Dsort -B (or whatever test configuration you must use)

Since the container is binding to your source, you can make edits from your IDE and continue to run build jobs.

Note
Docker containers can eat up disk space fast! From time to time, run docker system prune to clean out old images.

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.

spring-data-r2dbc's People

Contributors

mp911de avatar schauder avatar odrotbohm avatar gregturn avatar sdeleuze avatar christophstrobl avatar anbusampath avatar uaihebert avatar oshai avatar rdegnan avatar spring-operator avatar making avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.