DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Trending

  • Memory Leak Due to Time-Taking finalize() Method
  • Docker Base Images Demystified: A Practical Guide
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  1. DZone
  2. Data Engineering
  3. Data
  4. Spring Data and R2DBC by Example

Spring Data and R2DBC by Example

Take a look at this tutorial that show you how use R2DBC in a Spring project.

By 
moises zapata user avatar
moises zapata
·
May. 13, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
11.1K Views

Join the DZone community and get the full member experience.

Join For Free

R2DBC is a project that enables us to develop reactive programs API with relational databases, as we can do with databases that natively offer reactive drivers, like for example, Mongo or Cassandra.

Spring Data R2DBC is an abstraction of Spring to use repositories that support R2DBC and allows us a functional approach to interact with a relational database.

I use the following:

  1. Gradle 6.7.1
  2. Scala 2.12.6 ( I like this language :) )
  3. JDK 15
  4. Intellij IDEA
  5. Spring Boot 2.4.4

The project structure is:

Project Structure

The Gradle file contains:

Groovy
 




xxxxxxxxxx
1
42


 
1
plugins {
2
    id 'org.springframework.boot' version '2.4.4'
3
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
4
    id 'java'
5
    id 'scala'
6
}
7

          
8
group 'org.mazp.admin'
9
version '1.0-SNAPSHOT'
10

          
11
repositories {
12
    mavenCentral()
13
    maven { url 'https://repo.spring.io/milestone' }
14
    maven { url 'https://repo.spring.io/snapshot' }
15
}
16

          
17
dependencies {
18
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
19
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
20

          
21
    implementation 'org.scala-lang:scala-library:2.12.6'
22
    testImplementation 'org.scalatest:scalatest_2.12:3.2.3'
23
    testImplementation 'org.scala-lang:scala-library:2.12.6'
24

          
25
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
26
    implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'
27

          
28
    implementation  'dev.miku:r2dbc-mysql'
29
    implementation  'mysql:mysql-connector-java'
30

          
31
}
32

          
33
test { useJUnitPlatform() }
34

          
35
sourceSets {
36
    main { scala { srcDirs = ['src/main/scala'] } }
37
    test { scala { srcDirs = ['src/test/scala'] } }
38
}
39

          
40
springBoot {
41
    mainClass = 'com.mazp.admin.Main'
42
}



The properties files is:

Properties files
 




x


 
1
spring.r2dbc.url=r2dbc:mysql://localhost:3306/admin_r2dbc
2
spring.r2dbc.username=user_mysql
3
spring.r2dbc.password=password_user_mysql



The next class is used to map a row with an object:

Scala
 




xxxxxxxxxx
1
22


 
1
package com.mazp.admin.model
2

          
3
import org.springframework.data.annotation.Id
4
import org.springframework.data.relational.core.mapping.Table
5

          
6
@Table("admin")
7
class AdminObject {
8
  @Id private var idAdmin:Integer = null
9

          
10
  private var adminCode:String = null
11
  private var description:String = null
12

          
13
  def getDescription() = description
14
  def setDescription(usr:String) = this.description = usr
15

          
16
  def getAdminCode() = adminCode
17
  def setAdminCode(ctId:String) = adminCode = ctId
18

          
19
  def getIdAdmin() = idAdmin
20
  def setIdAdmin(ctId:Integer) = idAdmin = ctId
21
}
22

          



The repository is:

Scala
 




xxxxxxxxxx
1
16


 
1
package com.mazp.admin.respository
2

          
3
import com.mazp.admin.model.AdminObject
4
import org.springframework.data.repository.reactive.ReactiveCrudRepository
5
import reactor.core.publisher.Flux
6

          
7
trait AdminRepository extends ReactiveCrudRepository[AdminObject, Integer ]{
8

          
9
  /**
10
   * This method uses the convention name 
11
   * @param adminCode
12
   * @return
13
   */
14
  def findByAdminCode(adminCode:String):Flux[AdminObject]
15
}



The service class is:

Scala
 




xxxxxxxxxx
1
13


 
1
package com.mazp.admin.service
2

          
3
import com.mazp.admin.respository.AdminRepository
4
import org.springframework.beans.factory.annotation.Autowired
5
import org.springframework.stereotype.Service
6

          
7
@Service
8
class AdminService (@Autowired val adminRepository: AdminRepository) {
9

          
10
  def getAdmin(adminCode:String)  =
11
    adminRepository.findByAdminCode(adminCode)
12

          
13
}



The controller class is:

Scala
 




xxxxxxxxxx
1
17


 
1
package com.mazp.admin.controller
2

          
3
import com.mazp.admin.service.AdminService
4
import org.springframework.beans.factory.annotation.Autowired
5
import org.springframework.web.bind.annotation.{GetMapping, PathVariable, RequestMapping, RestControllerAdvice}
6

          
7

          
8
@RestControllerAdvice
9
@RequestMapping(Array("/admin"))
10
class AdminController(@Autowired val adminService: AdminService) {
11

          
12
  @GetMapping(Array("/{adminCode}"))
13
  def route(@PathVariable adminCode: String) = {
14
    adminService.getAdmin(adminCode)
15
  }
16

          
17
}



 The main class:

Scala
 




xxxxxxxxxx
1
12


 
1
package com.mazp.admin
2

          
3
import org.springframework.boot.SpringApplication
4
import org.springframework.boot.autoconfigure.{SpringBootApplication}
5

          
6
@SpringBootApplication
7
class Main
8

          
9
object Main extends App{
10
  SpringApplication.run(classOf[Main], args:_*)
11
}



The table admin is:

MySQL
 




xxxxxxxxxx
1
10


 
1
CREATE TABLE `admin` (
2
  `id_admin` int NOT NULL AUTO_INCREMENT,
3
  `admin_code` varchar(45) NOT NULL,
4
  `description` varchar(45) DEFAULT NULL,
5
  PRIMARY KEY (`id_admin`),
6
  UNIQUE KEY `admin_code_UNIQUE` (`admin_code`)
7
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
8

          
9
INSERT INTO `admin_r2dbc`.`admin`(`admin_code`,`description`) 
10
VALUES('ADMIN','Esto es para prueba R2DBC');



 When you run the project, you can call:

Running Project

Now, we use the curl command to test the service:

curl command to test service


Spring Framework Spring Data Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!