GithubHelp home page GithubHelp logo

buzzardo / gs-accessing-data-r2dbc Goto Github PK

View Code? Open in Web Editor NEW

This project forked from spring-guides/gs-accessing-data-r2dbc

0.0 1.0 0.0 299 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

Java 93.00% Shell 7.00%

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’ll build

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

Starting with Spring Initializr

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. This example needs the R2DBC and H2 dependencies. The following image shows the Initializr set up for this sample project:

initializr
Note
The preceding image shows the Initializr with Maven chosen as the build tool. You can also use Gradle. It also shows values of com.example and accesing-data-r2dbc as the Group and Artifact, respectively. You will use those values throughout the rest of this sample.

The following listing shows the pom.xml file created when you choose Maven:

link:complete/pom.xml[role=include]

The following listing shows the build.gradle file created when you choose Gradle:

link:complete/build.gradle[role=include]

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. Spring Boot’s auto-configuration picks up the schema.sql file during application startup to initialize the database schema.

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 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

bclozel avatar gregturn avatar mp911de avatar royclarkson avatar

Watchers

 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.