spring-boot - "JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation"升级到Spring Boot 2.7后出现异常

标签 spring-boot hibernate spring-data-jpa h2

将我的项目升级到 Spring Boot 2.7 后,我的测试开始失败并出现以下错误:

ERROR   ---[           main] o.h.engine.jdbc.spi.SqlExceptionHelper   :Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.MODEL(ID) ( /* key:1 */ CAST(1 AS BIGINT), 'Model 1 Description')"; SQL statement:
insert into model (id, description) values (default, ?, ?, ?, ?, ?, ?, ?) [23505-212]

这是我在 data.sql 中使用 H2 预加载测试数据的内容:

INSERT INTO Model(id, description) VALUES (1, 'Model 1 Description');

这是我的实体:

@Entity
public class Model {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String description;

    // ...

执行此测试时会触发错误:

@Test
void whenModelCreated_thenSuccess() {
    Model1 newModel = new Model("First Test Model");
    modelRepository.save(newModel);
    
    // ...
}

最佳答案

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

the H2 "migration-to-v2" guide中所示,标识列和序列的处理方式发生了变化。显然,H2 数据库引擎必须管理所有生成的 id 以便跟踪它们,并且通过显式指示要插入到数据库中的 id,我们绕过了数据库引擎,并产生了问题。

更改我的 data.sql INSERT 语句以使用 default 关键字,将其留给数据库引擎来负责分配id 本身, isso 已修复:

INSERT INTO Model(id, description) VALUES (default, 'Model 1 Description');

关于spring-boot - "JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation"升级到Spring Boot 2.7后出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72605646/

相关文章:

jsp - 无法使用 Servlet 3.1 使用 JSTL 1.2 获得 Tomcat 8.0

hibernate - Grails引发错误hbm2ddl.SchemaExport-HHH000389:不成功

java - Spring Data JPA 实体图不适用于 Spring Boot

java - Spring 启动 : "Scope ' request' is not active for the current thread"in Asynch method

java - StackOverflowError jackson 与 Spring

java - 如何解决org.hibernate.NonUniqueObjectException : a different object with the same identifier value was already associated with the session:

java - Spring Boot 2.0.0 循环 bean 依赖 EntityManger 和 SessionFactory

java - Spring 数据JPA : one-to-one instantiation problem: PersistentObjectException: detached entity passed to persist

java - 在保存实体之前避免 Spring Data JPA 选择

java - 运行项目时缺少 bean EmbeddedWebApplicationContext