R2DBC-响应式数据库

简单查询

基于全异步,响应式,消息驱动
用法:
1.导入驱动:导入连接池(r2dbc-pool),导入驱动(r2dbc-mysql)
2. 使用驱动提供的api操作
pom.xml

<properties><r2dbc-mysql.version>1.0.5</r2dbc-mysql.version>
</properties><dependencies><dependency><groupId>io.asyncer</groupId><artifactId>r2dbc-mysql</artifactId><version>${r2dbc-mysql.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

单元测试

    @Testpublic void testGetConnection() throws Exception{//1.获取连接工厂MySqlConnectionConfiguration config = MySqlConnectionConfiguration.builder().host("123.57.132.54").username("root").password("zyl000419").database("index_demo").build();MySqlConnectionFactory factory = MySqlConnectionFactory.from(config);//2.获取到连接,发送sqlMono.from(factory.create()).flatMapMany(connection ->connection.createStatement("SELECT * FROM t_author WHERE id = ?id").bind("id",1L).execute())//每一个连接会产生很多数据(result).flatMap(result -> {return result.map(readable -> {Long id = readable.get("id", Long.class);String name = readable.get("name", String.class);return new Author(id,name);});}).subscribe(System.out::println);System.in.read();}

参数赋值
在这里插入图片描述

spring data r2dbc-整合与自动配置

SpringBoot对r2dbc自动配置
R2dbcAutoConfiguration:主要配置连接工厂,连接池
R2dbcDataAutoConfiguration:
r2dbcEntityTemplate:操作数据库的响应式客户端,提供crud Api数据类型映射关系,转换器
自定义R2dbcCustomConversions转换器组件
数据类型 int -> integer; varchar->string
R2dbcRepositoriesAutoConfiguration:开启springboot声明式接口方式的crud
spring data 提供了基础的crud接口,不用写任何实现的情况下,可以直接具有crud功能
R2dbcTransactionManager:事物管理

导入相关依赖

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

编写application.yml配置
调整日志级别,打印sql语句

spring:r2dbc:url: r2dbc:mysql://your_host:3306username: rootpassword: your_passwordname: your_database
logging:level:org.springframework.r2dbc: debug

database client & r2dbcEntityTemplate api

创建数据库映射实体

@Data
@AllArgsConstructor
@NoArgsConstructor
@Table("t_author")
public class Author {private Long id;private String name;}

R2dbcEntityTemplate: crudApi,join操作不好做

    @Autowiredprivate R2dbcEntityTemplate template;@Testpublic void testR2dbcEntityTemplate() throws Exception{//1.构造查询条件Criteria criteria = Criteria.empty().and("id").is(1L).and("name").is("zyl");//2.封装为查询对象Query query = Query.query(criteria);template.select(query, Author.class).subscribe(System.out::println);System.in.read();}

DatabaseClient:数据库客户端,贴近底层,join操作好做

    @Autowiredprivate DatabaseClient databaseClient;@Testpublic void testJoin() throws IOException {databaseClient.sql("SELECT  * FROM t_author WHERE id = ?id").bind("id",1L).fetch().all().map(map -> {String id = String.valueOf(map.get("id"));String name = String.valueOf(map.get("name"));return new Author(Long.valueOf(id), name);}).subscribe(System.out::println);System.in.read();}

spring data r2dbc

开启r2dbc仓库功能,jpa

@EnableR2dbcRepositories
@Configuration
public class R2dbcConfig {}

1.写Repositories接口,默认继承一些crud方法
QBC: Query By Ctiteric
QBE: Query By Example

@Repository
public interface AuthorRepositories extends R2dbcRepository<Author,Long> {}

测试:
复杂调价查询:
1.QBE Api(不推荐)
2.自定义方法
3.自定义sql
repositeries起名有提示,按sql起名

@Repository
public interface AuthorRepositories extends R2dbcRepository<Author,Long> {/*** where id in ? and name like ?*/Flux<Author> findAllByIdInAndNameLike(Collection<Long> ids, String name);
}

测试复杂查询

    @Testpublic void testRepositories() throws IOException {authorRepositories.findAll().subscribe(System.out::println);authorRepositories.findAllByIdInAndNameLike(List.of(1L),"z%").subscribe(System.out::println);System.in.read();}

控制台打印sql

SELECT t_author.id, t_author.name 
FROM t_author 
WHERE t_author.id IN (?) AND (t_author.name LIKE ?)

缺点:仅限单表crud
测试多表复杂查询
自定义注解@Query(),指定sql语句
1-1查询:一个图书有一个作者
1-n查询:一个作者写了多本图书
实体类Book

@Data
@Table("t_book")
public class Book {@Idprivate Long id;private String title;private Long authorId;private LocalDateTime publishTime;}

repositorues

@Repository
public interface BookRepositories extends R2dbcRepository<Book,Long> {@Query("SELECT book.title,author.name " +"FROM index_demo.t_book book " +"LEFT JOIN index_demo.t_author author " +"ON book.author_id = author.id " +"WHERE book.id = :bookId")Mono<Book> findBookAndAuthor(Long bookId);
}

绑定查询参数:
在这里插入图片描述
自定义结果转换器

@ReadingConverter//读取数据库数据时,把row->book
public class BookConverter implements Converter<Row, Book> {@Overridepublic Book convert(Row source) {if (ObjectUtils.isEmpty(source)) {return new Book();}String title = source.get("title", String.class);String authorName = source.get("name", String.class);Book book = new Book();Author author = new Author();author.setName(authorName);book.setAuthor(author);book.setTitle(title);return book;}
}

配置自定义类型转换器

@EnableR2dbcRepositories
@Configuration
public class R2dbcConfig {/*** 将自己定义的转换器加入进去*/@Bean@ConditionalOnMissingBeanpublic R2dbcCustomConversions conversions () {return R2dbcCustomConversions.of(MySqlDialect.INSTANCE,new BookConverter());}}

测试

    @Testpublic void testQueryMulti() throws Exception{bookRepositories.findBookAndAuthor(1L).subscribe(System.out::println);System.in.read();}

总结:
1.spring data R2DBC 基础的CRUD用R2dbcRepository 提供好了
2.自定义复杂的sql(单表):@Query()
3.多表查询复杂结果集合:DatabaseClient自定义sql,自定义结果封装
@Query+自定义converter实现结果封装
自定义转换器问题:对以前crud产生影响
Converter<Row,Book>:把数据库每一行row,转换成book
工作时机:spring data发现方法签名只要是返回Book,利用自定义转换器工作
所有对Book结果封装都使用转换器,包括单表查询
解决方法1:新VO+新的Repositories+自定义类型转换器
BookauthorVO

@Data
public class BookAuthorVO {private Long id;private String title;private Long authorId;private LocalDateTime publishTime;private Author author;//每一本书有唯一作者
}

自定义BookAuthorRepositories

@Repository
public interface BookAuthorRepositories extends R2dbcRepository<BookAuthorVO,Long> {@Query("SELECT book.title,author.name " +"FROM index_demo.t_book book " +"LEFT JOIN index_demo.t_author author " +"ON book.author_id = author.id " +"WHERE book.id = :bookId")Mono<Book> findBookAndAuthor(@Param("bookId")Long bookId);
}

自定义BookAuthor转换器

@ReadingConverter//读取数据库数据时,把row->book
public class BookAuthorConverter implements Converter<Row, BookAuthorVO> {@Overridepublic BookAuthorVO convert(Row source) {if (ObjectUtils.isEmpty(source)) {return new BookAuthorVO();}String title = source.get("title", String.class);String authorName = source.get("name", String.class);BookAuthorVO book = new BookAuthorVO();Author author = new Author();author.setName(authorName);book.setAuthor(author);book.setTitle(title);return book;}
}

解决方法2:自定义转换器中增加判断
source.getMetaData.contains(“”)
让converter兼容更多表结构(推荐!!!)

@ReadingConverter//读取数据库数据时,把row->book
public class BookAuthorConverter implements Converter<Row, BookAuthorVO> {@Overridepublic BookAuthorVO convert(Row source) {if (ObjectUtils.isEmpty(source)) {return new BookAuthorVO();}String title = source.get("title", String.class);BookAuthorVO book = new BookAuthorVO();book.setTitle(title);if (source.getMetadata().contains("name")) {String authorName = source.get("name", String.class);Author author = new Author();author.setName(authorName);book.setAuthor(author);}return book;}
}

经验:
1-1/1-n都需要自定义结果集
spring data R2dbc:自定义converter指定结果封装
mybatis:自定义resultMap标签来封装

BufferUntilChanged操作

如果下一个判定值,比起上一个发生了变化,就开一个新buffer保存
如果没有变化,就保存到原buffer中
前提:数据已经提前排好序
groupBy:允许乱序
作者有很多图书. 1:n
sql

SELECT author.name,author.id,book.title
FROM index_demo.t_author author
LEFT JOIN index_demo.t_book book
ON author.id = book.author_id
WHERE author.id = 1;

测试

    @Testpublic void testAuthorBookTest() throws Exception {databaseClient.sql("SELECT author.name,author.id,book.title " +"FROM index_demo.t_author author " +"LEFT JOIN index_demo.t_book book " +"ON author.id = book.author_id " +"WHERE author.id = ?id").bind("id", 1L).fetch().all().bufferUntilChanged(rowMap -> Long.parseLong(String.valueOf(rowMap.get("id"))))//id发生变化,重新分组,若是对象比较,需重写equals()方法.map(list -> {if (CollectionUtils.isEmpty(list)) {return Collections.emptyList();}List<Book> bookList = list.stream().map(item -> {String title = String.valueOf(item.get("title"));return Book.builder().title(title).build();}).toList();return Author.builder().id(Long.valueOf(String.valueOf(list.get(0).get("id")))).name(String.valueOf(list.get(0).get("name"))).bookList(bookList);}).subscribe(System.out::println);System.in.read();}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/419316.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux重定向:深入理解与实践

&#x1f3ac;慕斯主页&#xff1a;修仙—别有洞天 ♈️今日夜电波&#xff1a;晴る—ヨルシカ 0:20━━━━━━️&#x1f49f;──────── 4:30 &#x1f504; ◀️ ⏸ ▶️ ☰ &…

【cucumber】cluecumber-report-plugin生成测试报告

cluecumber为生成测试报告的第三方插件&#xff0c;可以生成html测报&#xff0c;该测报生成需以本地json测报的生成为基础。 所以需要在测试开始主文件标签CucumberOptions中&#xff0c;写入生成json报告。 2. pom xml文件中加入插件 <!-- 根据 cucumber json文件 美化测…

【llm 微调code-llama 训练自己的数据集 一个小案例】

这也是一个通用的方案&#xff0c;使用peft微调LLM。 准备自己的数据集 根据情况改就行了&#xff0c;jsonl格式&#xff0c;三个字段&#xff1a;context, answer, question import pandas as pd import random import jsondata pd.read_csv(dataset.csv) train_data data…

【开源】基于JAVA的CRM客户管理系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块三、系统设计3.1 用例设计3.2 E-R 图设计3.3 数据库设计3.3.1 客户表3.3.2 商品表3.3.3 客户跟踪表3.3.4 客户消费表3.3.5 系统角色表 四、系统展示五、核心代码5.1 查询客户5.2 新增客户跟踪记录5.3 新增客户消费订单5.4 查…

复现PointNet++(语义分割网络):Windows + PyTorch + S3DIS语义分割 + 代码

一、平台 Windows 10 GPU RTX 3090 CUDA 11.1 cudnn 8.9.6 Python 3.9 Torch 1.9.1 cu111 所用的原始代码&#xff1a;https://github.com/yanx27/Pointnet_Pointnet2_pytorch 二、数据 Stanford3dDataset_v1.2_Aligned_Version 三、代码 分享给有需要的人&#xf…

操作系统-操作系统体系结构(内核 外核 模块化 宏内核 微内核 分层结构)

文章目录 大内核与微内核总览操作系统的内核大内核与微内核的性能差异小结 分层结构与模块化与外核总览分层结构模块化宏内核&#xff0c;微内核外核 大内核与微内核 总览 操作系统的内核 操作系统的核心功能在内核中 对于与硬件关联程度的程序 由于进程管理&#xff0c;存…

L1-067 洛希极限(Java)

科幻电影《流浪地球》中一个重要的情节是地球距离木星太近时&#xff0c;大气开始被木星吸走&#xff0c;而随着不断接近地木“刚体洛希极限”&#xff0c;地球面临被彻底撕碎的危险。但实际上&#xff0c;这个计算是错误的。 洛希极限&#xff08;Roche limit&#xff09;是一…

OpenMV入门

1. 什么是OpenMV OpenMV 是一个开源&#xff0c;低成本&#xff0c;功能强大的 机器视觉模块。 OpenMV上的机器视觉算法包括 寻找色块、人脸检测、眼球跟踪、边缘检测、标志跟踪 等。 以STM32F427CPU为核心&#xff0c;集成了OV7725摄像头芯片&#xff0c;在小巧的硬件…

小程序学习-19

Vant Weapp - 轻量、可靠的小程序 UI 组件库 ​​​​​ Vant Weapp - 轻量、可靠的小程序 UI 组件库 安装出现问题&#xff1a;rollbackFailedOptional: verb npm-session 53699a8e64f465b9 解决办法&#xff1a;http://t.csdnimg.cn/rGUbe Vant Weapp - 轻量、可靠的小程序…

海外媒体发稿:满足要求的二十个爆款文案的中文标题-华媒舍

爆款文案是指在营销和推广方面非常受欢迎和成功的文案。它们能够吸引读者的眼球&#xff0c;引发浏览者的兴趣&#xff0c;最终促使他们采取行动。本文将介绍二十个满足要求的爆款文案的中文标题&#xff0c;并对每个标题进行拆解和描述。 1. "XX 绝对不能错过的十大技巧…

RHEL - 更新升级软件或系统

《OpenShift / RHEL / DevSecOps 汇总目录》 文章目录 小版本软件更新yum update 和 yum upgrade 的区别升级软件和升级系统检查软件包是否可升级指定升级软件使用的发行版本方法1方法2方法3方法4 查看软件升级类型更新升级指定的 RHSA/RHBA/RHEA更新升级指定的 CVE更新升级指定…

第36集《佛法修学概要》

请大家打开讲义第九十六面&#xff0c;我们讲到禅定的修学方便。 在我们发了菩提心&#xff0c;安住菩萨种性以后&#xff0c;我们开始操作六度的法门。六度的法门&#xff0c;它有两个不同的差别的内容&#xff0c;一种是成就我们的善业力&#xff0c;另外一种&#xff0c;是…