升级到 Spring Boot 2.7 时测试失败 - “CommandAcceptanceException:执行 DDL 时出错”

Ger*_*oza 2 hibernate h2 spring-data-jpa spring-boot

升级到 Boot 2.7 后,使用嵌入式 H2 数据库的集成测试开始失败。

我在日志中看到此警告消息,但不清楚原因或解决方案:

WARN 8053 ---[           main] o.h.t.s.i.ExceptionHandlerLoggedImpl     :GenerationTarget encountered exception accepting command : Error executing DDL "create table user (id bigint generated by default as identity, email varchar(255) not null, name varchar(255), primary key (id))" via JDBC Statement

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table user (id bigint generated by default as identity, email varchar(255) not null, name varchar(255), primary key (id))" via JDBC Statement
...
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement "create table [*]user (id bigint generated by default as identity, email varchar(255) not null, name varchar(255), primary key (id))"; expected "identifier"; SQL statement:
create table user (id bigint generated by default as identity, email varchar(255) not null, name varchar(255), primary key (id)) [42001-212]
...

Run Code Online (Sandbox Code Playgroud)

看来我的User表在升级后没有创建,从而使我的测试失败。

Ger*_*oza 6

Boot 2.7 似乎升级到了对 2.x 的 H2 依赖,这不向后兼容并引入了一些更改: https ://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7-Release-注释#h2-21

问题是User现在是一个关键字/保留字(H2“迁移到 v2”指南对我来说不是很有帮助;它提到添加了新关键字,但没有提供指向 的链接):

https://www.h2database.com/html/advanced.html#keywords

所以,我必须做的是使用“带引号的名称”来定义实体的表名称(似乎我也可以在表注释中使用反引号而不是转义双引号):

@Table(name="\"user\"")
@Entity
public class User {
...
Run Code Online (Sandbox Code Playgroud)

我还必须在data.sql该表的文件中使用双引号:

INSERT INTO "user"(id, email, name) VALUES(1, 'test@user.com', 'Test User');
Run Code Online (Sandbox Code Playgroud)

注意:迁移指南还提到了使用该SET NON_KEYWORDS命令作为解决方法的可能性,但它也不鼓励这样做。