Coder Social home page Coder Social logo

spring-guides / gs-accessing-data-r2dbc Goto Github PK

View Code? Open in Web Editor NEW
47.0 20.0 21.0 534 KB

Accessing data with R2DBC :: Learn how to access relational data with the reactive protocol R2DBC

Home Page: https://spring.io/guides/gs/accessing-data-r2dbc

License: Apache License 2.0

Java 93.44% Shell 6.56%

gs-accessing-data-r2dbc's Introduction

This guide walks you through the process of building an application that uses Spring Data R2DBC to store and retrieve data in a relational database using reactive database drivers.

What You Will build

You will build an application that stores Customer POJOs (Plain Old Java Objects) in a memory-based database.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Data R2DBC and H2 Database.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
Note
You can also fork the project from Github and open it in your IDE or other editor.

Define a Schema

In this example, you store Customer objects, each annotated as a R2DBC entity. The following listing shows the SQL schema class (in src/main/resources/schema.sql):

link:complete/src/main/resources/schema.sql[role=include]

Here you have a customer table with three columns: id, first_name, and last_name. The id column is auto-incremented, the other columns follow the default snake case naming scheme. Later on, we need to register a ConnectionFactoryInitializer to pick up the schema.sql file during application startup to initialize the database schema. Because the H2 driver is on the class path and we haven’t specified a connection URL, Spring Boot starts an embedded H2 database.

Define a Simple Entity

In this example, you store Customer objects, each annotated as a R2DBC entity. The following listing shows the Customer class (in src/main/java/com/example/accessingdatar2dbc/Customer.java):

link:complete/src/main/java/com/example/accessingdatar2dbc/Customer.java[role=include]

Here you have a Customer class with three attributes: id, firstName, and lastName. The Customer class is minimally annotated. The id property is annotated with @Id so that Spring Data R2DBC can identify the primary key. By default, primary keys are assumed to be generated by the database on INSERT.

The other two properties, firstName and lastName, are left unannotated. It is assumed that they are mapped to columns that share the same names as the properties themselves.

The convenient toString() method print outs the customer’s properties.

Create Simple Queries

Spring Data R2DBC focuses on using R2DBC as underlying technology to store data in a relational database. Its most compelling feature is the ability to create repository implementations, at runtime, from a repository interface.

To see how this works, create a repository interface that works with Customer entities as the following listing (in src/main/java/com/example/accessingdatar2dbc/CustomerRepository.java) shows:

link:complete/src/main/java/com/example/accessingdatar2dbc/CustomerRepository.java[role=include]

CustomerRepository extends the ReactiveCrudRepository interface. The type of entity and ID that it works with, Customer and Long, are specified in the generic parameters on ReactiveCrudRepository. By extending ReactiveCrudRepository, CustomerRepository inherits several methods for working with Customer persistence, including methods for saving, deleting, and finding Customer entities using reactive types.

Spring Data R2DBC also lets you define other query methods by annotating these with @Query. For example, CustomerRepository includes the findByLastName() method.

In a typical Java application, you might expect to write a class that implements CustomerRepository. However, that is what makes Spring Data R2DBC so powerful: You need not write an implementation of the repository interface. Spring Data R2DBC creates an implementation when you run the application.

Now you can wire up this example and see what it looks like!

Create an Application Class

Spring Initializr creates a simple class for the application. The following listing shows the class that Initializr created for this example (in src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java):

link:initial/src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java[role=include]

Now you need to modify the simple class that the Initializr created for you. To get output (to the console, in this example), you need to set up a logger. Then you need to set up the initializer to setup the schema and some data and use it to generate output. The following listing shows the finished AccessingDataR2dbcApplication class (in src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java):

link:complete/src/main/java/com/example/accessingdatar2dbc/AccessingDataR2dbcApplication.java[role=include]

The AccessingDataR2dbcApplication class includes a main() method that puts the CustomerRepository through a few tests. First, it fetches the CustomerRepository from the Spring application context. Then it saves a handful of Customer objects, demonstrating the save() method and setting up some data to use. Next, it calls findAll() to fetch all Customer objects from the database. Then it calls findById() to fetch a single Customer by its ID. Finally, it calls findByLastName() to find all customers whose last name is "Bauer".

R2DBC is a reactive programming technology. At the same time we’re using it in a synchronized, imperative flow and that is why we’re required to synchronize each call with a variant of the block(…) method. In a typical reactive application, the resulting Mono or Flux would represent a pipeline of operators that is handed back to a web controller or event processor that subscribes to the reactive sequence without blocking the calling thread.

Note
By default, Spring Boot enables R2DBC repository support and looks in the package (and its subpackages) where @SpringBootApplication is located. If your configuration has R2DBC repository interface definitions located in a package that is not visible, you can point out alternate packages by using @EnableR2dbcRepositories and its type-safe basePackageClasses=MyRepository.class parameter.

When you run your application, you should see output similar to the following:

== Customers found with findAll():
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=2, firstName='Chloe', lastName='O'Brian']
Customer[id=3, firstName='Kim', lastName='Bauer']
Customer[id=4, firstName='David', lastName='Palmer']
Customer[id=5, firstName='Michelle', lastName='Dessler']

== Customer found with findOne(1L):
Customer[id=1, firstName='Jack', lastName='Bauer']

== Customer found with findByLastName('Bauer'):
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=3, firstName='Kim', lastName='Bauer']

Summary

Congratulations! You have written a simple application that uses Spring Data R2DBC to save objects to and fetch them from a database, all without writing a concrete repository implementation.

gs-accessing-data-r2dbc's People

Contributors

ahianzhang avatar bclozel avatar brutus5000 avatar gregturn avatar luizgustavocosta avatar mp911de avatar robertmcnees avatar royclarkson avatar siwekmichal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gs-accessing-data-r2dbc's Issues

Upgrade Spring Boot to the latest version

Update the guide to use the most recent Spring Boot version.

To do so, change the Spring Boot version in:

initial/build.gradle
initial/pom.xml
complete/build.gradle
complete/pom.xml

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.