RxSqlUtils(base R2dbc)

一、前言

随着 Solon 3.0 和 Solon-Rx 3.0 发布,又迎来了的 RxSqlUtils 扩展插件,用于“响应式”操作数据库。RxSqlUtils 是基于 R2dbc 和 Reactor 接口构建。极简风格,就像个工具类,故名:RxSqlUtils。

尤其在 solon-web-rx 和 Solon Cloud Gateway(基于纯响应式构建) 场景开发时,RxSqlUtils 会是最好的良配。

二、RxSqlUtils 使用

1、引入依赖

<dependency>     <groupId>org.noear</groupId>     <artifactId>solon-data-rx-sqlutils</artifactId> </dependency> 

2、新建数据库表(for H2)

CREATE TABLE `user`  (   `id` bigint(20) not null,   `name` varchar(255)  DEFAULT NULL,   `title` varchar(255)  DEFAULT NULL,   PRIMARY KEY (`id`) ); 

3、定义实体类

使用了 lombok 的注解。

@Data public class User {     private Long id;     private String name;     private String title; } 

4、添加数据源配置

solon.dataSources:   user!: # ‘!’结尾表示默认数据源     class: "org.noear.solon.data.datasource.R2dbcConnectionFactory"     r2dbcUrl: "r2dbc:h2:mem:///test;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL;DATABASE_TO_LOWER=TRUE;IGNORECASE=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE" 

5、注入 RxSqlUtils 并使用

注入(这样就可以用了)

@Component public class UserDao {     @Inject     private RxSqlUtils sqlUtils; } 

查询操作

public Flux<User> getAllUsers() {     return sqlUtils.sql("select * from user")                    .queryRowList(User.class); }  

新增操作

public Mono<Long> addUser(User user) {     return sqlUtils.sql("INSERT INTO user (name , title) VALUES (?,?)", user.getName(), user.getTitle())                    .updateReturnKey(Long.class); } 

更新操作

public Mono<Long> updateUser(User user) {     return sqlUtils.sql("UPDATE user SET name=?, title=? WHERE id=?", user.getName(), user.getTitle(), user.getId())                    .update(); } 

总结

使用 RxSqlUtils 可以完成数据库的响应式操作,也有更好的透明性,使用简单和直接。

发表评论

评论已关闭。

相关文章