简体   繁体   English

使用 Spring 数据 R2DBC 查找/修改/保存或更新插入

[英]Find/Modify/Save or Upsert with Spring Data R2DBC

I'm trying to wrap my head around reactive programming, specifically with Spring and Spring Data R2DBC.我试图围绕反应式编程,特别是 Spring 和 Spring Data R2DBC。 One thing that would help me understand it better is to do a find/modify/save or "upsert" of an object.可以帮助我更好地理解它的一件事是对 object 进行查找/修改/保存或“更新插入”。 A traditional interaction might look like this:传统的交互可能如下所示:

Book save(Book book) {

   Book existing = repository.findByIsbn(book.getIsbn())

   if (existing != null) {
     return repository.save(found.copyMutableValuesFrom(book));
   }

   return repository.save(book);
}

How might this look with Monos? Monos 看起来如何? I understand how to do a straight find, or a straight save, but a more complicated find/update/save or upsert is eluding me.我了解如何进行直接查找或直接保存,但更复杂的查找/更新/保存或 upsert 让我望而却步。

Thanks.谢谢。

It will be more or less like this for your requirement.根据您的要求,它或多或少会像这样。

@Transactional
Mono<Book> save(Book book){
    return repository.findByIsbn(book.getIsbn())
                    .flatMap(found -> repository.save(found.copyMutableValuesFrom(book)))
                    .switchIfEmpty(repository.save(book));  
}
  1. ReactiveCrudRepository returns Mono<Book> when you call findById(something like Optional<Book> - if it is your custom method, make it return Mono<Book> ) ReactiveCrudRepository 在您调用 findById 时返回Mono<Book> (类似于Optional<Book> - 如果它是您的自定义方法,则使其返回Mono<Book>
  2. If the book is present second statement is executed where we update the existing book如果这本书存在,则在我们更新现有书籍的地方执行第二条语句
  3. if the book is not found, 3rd statement is executed where we save the new book.如果找不到这本书,则在我们保存新书的地方执行第三条语句。

It returns a Mono<Book>它返回一个Mono<Book>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM