我在 Spring Boot 中遇到 PK 违规(初始数据在 data.sql 中),经过调查,我发现如果我将 pom.xml 中的版本从 2.7 降级到 2.6.7,那么一切都会正常。 我正在使用H2数据库
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version> <!-- will not work -->
<!-- <version>2.6.7</version> will work -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
这是实体
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
}
有什么变化?我错过了什么?
我也有同样的问题。
我的 @GenerateValue(strategy = GenerationType.IDENTITY) 在 Spring Boot 2.6.8 上运行良好(默认为 H2 1.4.200)。
更改为 Spring Boot 2.7.0(默认为 H2 2.1.212)时,它停止处理上述主键违规问题。
我已经能够升级到 Spring Boot 2.7.0 并保留之前的 H2 版本:
<properties>
<h2.version>1.4.200</h2.version>
</properties>
同样的问题,
我认为这不仅仅是H2版本的问题,因为我在spring boot 2.6.7中使用H2 2.1.212没有任何问题,升级到spring 2.7.0后出现问题
对我有用的东西:我在
src/main/resources
和src/test/resources
有sql初始化文件。如果我删除 data.sql
处的 src/main/resources
,问题就会消失。 Spring 2.7.0 发生了一些变化
最近也遇到这个问题。 Hibernate 似乎不知道初始值被加载到数据库中,因此您必须在 sql 脚本中指定 id 计数的开始位置。因此,我在 h2 数据库的 data.sql 脚本中添加了以下 sql 命令:
ALTER TABLE your_table ALTER COLUMN id RESTART WITH 21;
希望这有帮助