【问题标题】:"JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation" Exception after upgrading to Spring Boot 2.7升级到Spring Boot 2.7后出现“JdbcSQLIntegrityConstraintViolationException:唯一索引或主键违规”异常
【发布时间】:2022-06-13 23:50:11
【问题描述】:

将我的项目升级到 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);
    
    // ...
}

【问题讨论】:

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


    【解决方案1】:

    似乎 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 以跟踪它们,并且通过显式指示要插入 DB 的 id,我们绕过了数据库引擎,并产生了问题。

    将我的 data.sql INSERT 语句更改为使用 default 关键字,让 DB 引擎负责分配 id 本身,这个 isso 得到了修复:

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

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 2021-08-16
      • 2019-02-09
      • 2015-03-05
      • 2019-12-24
      • 2014-12-27
      • 2019-09-28
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多