11 Şubat 2021 Perşembe

SpringData R2DBC DatabaseClient Sınfı

Giriş
Şu satırı dahil ederiz. Normalde R2dbcRepository sınıfını kullanmak lazım. Eğer custom bir iş yapılacaksa bu sınıf kullanılabilir.
import org.springframework.data.r2dbc.core.DatabaseClient;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Update;
import org.springframework.stereotype.Repository;
delete metodu
Örnek
Şöyle yaparız
public Mono<Boolean> deleteBook(UUID id){
  return databaseClient.delete()
    .from(Book.class).matching(Criteria.where("id").is(id)).then().thenReturn(true);
}
insert metodu
Örnek
Şöyle yaparız
public Mono<UUID> createBook(Book book){
  UUID bookId = UUID.randomUUID();
  book.setId(bookId);

  return databaseClient.insert().into(Book.class).using(book).then()
.thenReturn(bookId);
}
select metodu
Örnek
Şöyle yaparız
@Repository
public class BookRepository {

  @Autowired
  private DatabaseClient databaseClient;

  public Mono<Book> getBook(UUID id){
    return databaseClient.select()
      .from(Book.class)
      .matching(Criteria.where("id").is(id))
      .fetch()
      .one();
  }

  public Flux<Book> getBooks(){
    return databaseClient.select().from(Book.class).fetch().all();
  }
}
sql metodu
Örnek
Şöyle yaparız
@Repository
@RequiredArgsConstructor
public class AuthorCustomRepository {

  private final DatabaseClient databaseClient;

  public Flux<Author> findAll() {
    return databaseClient.sql("SELECT  "
      + "book.id as bookId, book.title as bookName, book.date_of_parution "
+ "as dateOfParution, "
      + "author.id as authorId, author.name as authorName "
      + "FROM author "
      + "JOIN book on author.id = book.author "
      + "ORDER BY authorId")
    .fetch()
    .all()
    .bufferUntilChanged( result -> result.get("authorId"))
    .map(list -> {
      AuthorBuilder author = Author.builder();
      author.name(String.valueOf(list.get(0).get("authorName")));
      author.id((UUID) list.get(0).get("authorId"));
      author.books(
list.stream()
.map(map -> {
  return Book.builder()
    .title((String) map.get("bookName"))
    .id((UUID) map.get( "bookId"))
    .dateOfParution((LocalDate) map.get("dateOfParution"))
    .build();
})
        .collect(Collectors.toList())
      );
      return author.build();
    });
  }
}
update metodu
Örnek
Şöyle yaparız
public Mono<String> updateBook(UUID ID,Book book){
  return databaseClient.update().table("books")
.using(Update.update("name",book.getName())).matching(Criteria.where("id").is(ID))
    .then().thenReturn("Success");
}

Hiç yorum yok:

Yorum Gönder