示例堆栈:Spring Data R2dbc 1.0.0.RELEASE、R2dbc Mssql 0.8,完整代码在这里。
初始化脚本:
use tempdb;
IF OBJECT_ID(N'dbo.posts', N'U') IS NULL
BEGIN
CREATE TABLE posts (
id BIGINT NOT NULL IDENTITY(1,1) PRIMARY KEY,
title VARCHAR (50) NOT NULL,
content VARCHAR (50) NOT NULL,
createdAt DATETIME,
updatedAt DATETIME
)
END;
保存数据并从中获取生成的密钥时DataInitializer
。
@Component
@Slf4j
class DataInitializer {
private final DatabaseClient databaseClient;
public DataInitializer(DatabaseClient databaseClient) {
this.databaseClient = databaseClient;
}
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
log.info("start data initialization...");
this.databaseClient.delete().from("posts")
.then().
and(
this.databaseClient.insert()
.into("posts")
//.nullValue("id", Integer.class)
.value("title", "First post title")
.value("content", "Content of my first post")
.map((r, m) -> r.get( 0, BigDecimal.class)).all()
.log()
)
.thenMany(
this.databaseClient.select()
.from("posts")
.orderBy(Sort.by(desc("id")))
.as(Post.class)
.fetch()
.all()
.log()
)
.subscribe(null, null, () -> log.info("initialization is done..."));
}
}
如果我在行中使用Integer
orLong
而不是,它将引发错误,指示无法解码类型 [java.lang.Long] 的值,名称 [GENERATED_KEYS] 服务器类型 [numeric],它不是架构脚本中定义的,我必须使用 a才能使其工作。BigDecimal
.map((r, m) -> r.get( 0, BigDecimal.class)).all()
bigint
BigDecimal