欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

如何在Spring data中使用r2dbc詳解

 更新時間:2020年11月03日 09:51:37   作者:程序那些事  
這篇文章主要給大家介紹了關(guān)于如何在Spring data中使用r2dbc的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

上篇文章我們講到了怎么在Spring webFlux中使用r2dbc,今天我們看一下怎么使用spring-data-r2dbc這個Spring data對r2dbc的封裝來進行r2dbc操作。

依賴關(guān)系

要使用Spring-datea-r2dbc需要配置下面的依賴關(guān)系:

<dependencies>
  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-r2dbc</artifactId>
  <version>2.3.3.RELEASE</version>
 </dependency>

  <!-- R2DBC H2 Driver -->
  <dependency>
   <groupId>io.r2dbc</groupId>
   <artifactId>r2dbc-h2</artifactId>
   <version>${r2dbc-h2.version}</version>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-webflux</artifactId>
  </dependency>

數(shù)據(jù)庫連接配置

Spring-data-r2dbc使用的是R2dbcProperties來進行配置文件的讀取:

簡單看一下R2dbcProperties的定義:

@ConfigurationProperties(prefix = "spring.r2dbc")
public class R2dbcProperties {

 /**
  * Database name. Set if no name is specified in the url. Default to "testdb" when
  * using an embedded database.
  */
 private String name;

 /**
  * Whether to generate a random database name. Ignore any configured name when
  * enabled.
  */
 private boolean generateUniqueName;

 /**
  * R2DBC URL of the database. database name, username, password and pooling options
  * specified in the url take precedence over individual options.
  */
 private String url;

 /**
  * Login username of the database. Set if no username is specified in the url.
  */
 private String username;

 /**
  * Login password of the database. Set if no password is specified in the url.
  */
 private String password;

相應(yīng)的,看一下我們的配置文件是怎么樣的:

spring.r2dbc.url=r2dbc:h2:mem://./testdb
spring.r2dbc.username=sa
spring.r2dbc.password=password

這里,我們使用的是H2數(shù)據(jù)庫。

數(shù)據(jù)庫初始化

數(shù)據(jù)庫初始化過程中,我們需要創(chuàng)建一個users表格,這里我們在一個initDatabase bean中實現(xiàn):

@Bean
 public ApplicationRunner initDatabase(DatabaseClient client, UsersDao usersDao) {
  List<String> statements = Arrays.asList(
    "DROP TABLE IF EXISTS USERS;",
    "CREATE TABLE IF NOT EXISTS USERS ( id SERIAL PRIMARY KEY, firstname VARCHAR(100) NOT NULL, lastname VARCHAR(100) NOT NULL);");

  statements.forEach(sql -> executeSql(client,sql)
    .doOnSuccess(count -> log.info("Schema created, rows updated: {}", count))
    .doOnError(error -> log.error("got error : {}",error.getMessage(),error))
    .subscribe()
  );

  return args ->getUser().flatMap(usersDao::save).subscribe(user -> log.info("User saved: {}", user));

 }

 private Flux<Users> getUser() {
  return Flux.just(new Users(null, "John", "Doe"), new Users(null, "Jane", "Doe"));
 }

 private Mono<Integer> executeSql(DatabaseClient client, String sql) {
  return client.execute(sql).fetch().rowsUpdated();
 }

上面的例子中,我們創(chuàng)建數(shù)據(jù)庫分為了兩部分,第一部分是數(shù)據(jù)庫schema的操作,我們執(zhí)行了drop和create table的操作。

第二部分是向數(shù)據(jù)庫表中插入數(shù)據(jù)。

注意,上面的兩部分操作都需要執(zhí)行subscribe操作,以觸發(fā)真正的Reactive操作。

DAO操作

在DAO操作之前,我們需要創(chuàng)建Users entity:

@Data
@AllArgsConstructor
public class Users {

 @Id
 private Integer id;
 private String firstname;
 private String lastname;

 boolean hasId() {
  return id != null;
 }
}

再看一下我們創(chuàng)建的UserDao:

public interface UsersDao extends ReactiveCrudRepository<Users, Long> {

 @Query("select id, firstname, lastname from users c where c.lastname = :lastname")
 Flux<Users> findByLastname(String lastname);
}

注意,這里并不需要添加@Component注解,因為我們繼承了ReactiveCrudRepository,會自動幫我們創(chuàng)建UsersDao的實例,我們直接使用就可以了。

ReactiveCrudRepository為我們封裝了一些DAO的基本操作,比如save,saveAll, findById ,existsById等基礎(chǔ)操作。

當然,我們也可以自定義自己的SQL語句,比如上面的findByLastname。

Service操作和Transaction

我們看一下怎么使用UserDao來進行具體的方法操作:

@Component
public class UsersService {

 @Resource
 private UsersDao usersDao;

 @Transactional
 public Mono<Users> save(Users user) {

  return usersDao.save(user).map(it -> {

   if (it.getFirstname().equals("flydean")) {
    throw new IllegalStateException();
   } else {
    return it;
   }
  });
 }

}

上面我們創(chuàng)建了一個save方法,用來保存相應(yīng)的User對象。

controller

最后,我們創(chuàng)建一個controller來對外暴露相應(yīng)的方法:

@RestController
@RequiredArgsConstructor
public class UsersController {

 private final UsersDao usersDao;

 @GetMapping("/users")
 public Flux<Users> findAll() {
  return usersDao.findAll();
 }
}

好了,現(xiàn)在我們的程序已經(jīng)寫好了,可以進行測試了。

運行程序,執(zhí)行:

curl "localhost:8080/users" 
[{"id":1,"firstname":"John","lastname":"Doe"},{"id":2,"firstname":"Jane","lastname":"Doe"}]%

可以看到取出了相應(yīng)的結(jié)果。

完美,實驗成功。

本文的代碼: spring-data-r2dbc

總結(jié)

到此這篇關(guān)于如何在Spring data中使用r2dbc的文章就介紹到這了,更多相關(guān)Spring data使用r2dbc內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Eclipse常用快捷鍵大全

    Eclipse常用快捷鍵大全

    這篇文章主要介紹了Eclipse常用快捷鍵大全,較為詳細的針對eclipse中各種應(yīng)用中使用快捷鍵進行了分類總結(jié),具有一定參考借鑒價值,需要的朋友可以參考下
    2015-11-11
  • Java中的引用和動態(tài)代理的實現(xiàn)詳解

    Java中的引用和動態(tài)代理的實現(xiàn)詳解

    這篇文章主要介紹了Java中的引用和動態(tài)代理的實現(xiàn)詳解,涉及Java中的引用類型,JVMGC的可達性分析,代理模式等相關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • SpringBoot中Dozer的使用小結(jié)

    SpringBoot中Dozer的使用小結(jié)

    dozer是用來兩個對象之間屬性轉(zhuǎn)換的工具,有了這個工具之后,我們將一個對象的所有屬性值轉(zhuǎn)給另一個對象時,就不需要再去寫重復(fù)的set和get方法了,下面介紹下SpringBoot中Dozer的使用,感興趣的朋友一起看看吧
    2022-03-03
  • idea快速搭建spring cloud注冊中心與注冊的方法

    idea快速搭建spring cloud注冊中心與注冊的方法

    這篇文章主要介紹了idea快速搭建spring cloud注冊中心與注冊的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Spring?Data?JPA映射自定義實體類操作

    Spring?Data?JPA映射自定義實體類操作

    這篇文章主要介紹了Spring?Data?JPA映射自定義實體類操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • IDEA在plugins里搜不到mybatisx插件的解決方法

    IDEA在plugins里搜不到mybatisx插件的解決方法

    本文主要介紹了IDEA在plugins里搜不到mybatisx插件的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • MybatisPlus使用Mybatis的XML的動態(tài)SQL的功能實現(xiàn)多表查詢

    MybatisPlus使用Mybatis的XML的動態(tài)SQL的功能實現(xiàn)多表查詢

    本文主要介紹了MybatisPlus使用Mybatis的XML的動態(tài)SQL的功能實現(xiàn)多表查詢,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-11-11
  • Java中的重要核心知識點之繼承詳解

    Java中的重要核心知識點之繼承詳解

    繼承是java面向?qū)ο缶幊碳夹g(shù)的一塊基石,因為它允許創(chuàng)建分等級層次的類。繼承就是子類繼承父類的特征和行為,使得子類對象(實例)具有父類的實例域和方法,或子類從父類繼承方法,使得子類具有父類相同的行為
    2021-10-10
  • Spring Cloud Feign簡單使用詳解

    Spring Cloud Feign簡單使用詳解

    本篇文章主要介紹了Spring Cloud Feign簡單使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • java對double數(shù)組排序示例分享

    java對double數(shù)組排序示例分享

    這篇文章主要介紹了java對double數(shù)組排序示例,代碼簡單,下面我們直接上代碼,需要的朋友可以參考下
    2014-03-03

最新評論