目录
1、导入R2DBC依赖
-
-
-
io.asyncer -
r2dbc-mysql -
1.0.5 -
-
-
-
org.springframework.boot -
spring-boot-starter-data-r2dbc -
2、编写配置
- spring:
- r2dbc:
- password: 123456
- username: root
- url: r2dbc:mysql://localhost:3306/test
- name: test
- @Repository
- public interface AuthorRepositories extends R2dbcRepository
{ -
- //默认继承了一堆CRUD方法; 像mybatis-plus
-
- //QBC: Query By Criteria
- //QBE: Query By Example
-
- //成为一个起名工程师 where id In () and name like ?
- //仅限单表复杂条件查询
- Flux
findAllByIdInAndNameLike(Collection id, String name) ; -
- //多表复杂查询
-
- @Query("select * from t_author") //自定义query注解,指定sql语句
- Flux
findHaha(); -
-
- // 1-1:关联
- // 1-N:关联
- //场景:
- // 1、一个图书有唯一作者; 1-1
- // 2、一个作者可以有很多图书: 1-N
-
-
-
- }
- ### 自定义Converter
-
- ```java
- package com.atguigu.r2dbc.config.converter;
-
- import com.atguigu.r2dbc.entity.TAuthor;
- import com.atguigu.r2dbc.entity.TBook;
- import io.r2dbc.spi.Row;
- import org.springframework.core.convert.converter.Converter;
- import org.springframework.data.convert.ReadingConverter;
-
- import java.time.Instant;
-
-
- @ReadingConverter //读取数据库数据的时候,把row转成 TBook
- public class BookConverter implements Converter
{
- @Override
- public TBook convert(Row source) {
- if(source == null) return null;
- //自定义结果集的封装
- TBook tBook = new TBook();
-
- tBook.setId(source.get("id", Long.class));
- tBook.setTitle(source.get("title", String.class));
-
- Long author_id = source.get("author_id", Long.class);
- tBook.setAuthorId(author_id);
- // tBook.setPublishTime(source.get("publish_time", Instant.class));
-
-
- TAuthor tAuthor = new TAuthor();
- tAuthor.setId(author_id);
- tAuthor.setName(source.get("name", String.class));
-
- tBook.setAuthor(tAuthor);
-
- return null;
- }
- }
- ```
-
- ### 配置生效
-
- ```java
- @EnableR2dbcRepositories //开启 R2dbc 仓库功能;jpa
- @Configuration
- public class R2DbcConfiguration {
-
-
- @Bean //替换容器中原来的
- @ConditionalOnMissingBean
- public R2dbcCustomConversions conversions(){
-
- //把我们的转换器加入进去; 效果新增了我们的 Converter
- return R2dbcCustomConversions.of(MySqlDialect.INSTANCE,new BookConverter());
- }
- }
- ```
-
- ## 2、编程式组件
-
- - R2dbcEntityTemplate
- - DatabaseClient
-
-
-