You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级Spring Boot 2.7.7(依赖Hibernate 5.6.14)后Sequence Generator生成负ID问题

问题描述
  • 升级至Spring Boot 2.7.7(依赖Hibernate 5.6.14)后,配置了@SequenceGenerator的实体新增记录时出现负ID问题
  • 数据库中已有正ID记录的表,序列生成逻辑正常;全新创建、使用步长为50的PostgreSQL序列的表,首次生成的ID为-47,后续依次按-46、-45……递增
  • 问题仅在全新数据库的单元测试场景下复现
原因分析

这是Hibernate 5.6.x版本针对PostgreSQL序列初始化的已知问题,核心触发点:

  • 当PostgreSQL序列未显式指定初始值(START WITH),或初始值设为1时,Hibernate内部计算序列下一个值的逻辑会因initialValue与步长(allocationSize)的冲突,导致生成负数ID
  • 已有记录的表因为序列已存在正的当前值,跳过了初始化阶段的错误计算,因此不受影响
解决方案

提供三种可行的修复方式:

  1. 对齐序列初始值与Hibernate配置
    创建PostgreSQL序列时,显式设置初始值为allocationSize + 1(步长为50时设为51),示例SQL:

    CREATE SEQUENCE your_entity_seq START WITH 51 INCREMENT BY 50;
    

    同时保证实体类的@SequenceGenerator配置匹配:

    @SequenceGenerator(
        name = "your_entity_seq",
        sequenceName = "your_entity_seq",
        initialValue = 1,
        allocationSize = 50
    )
    
  2. 修改Hibernate序列生成策略
    在配置文件中添加以下参数,强制Hibernate使用PostgreSQL原生的序列获取逻辑:

    # application.properties
    spring.jpa.properties.hibernate.id.new_generator_mappings=true
    spring.jpa.properties.hibernate.id.postgresql.use_get_generated_keys=true
    
  3. 升级Hibernate/ Spring Boot版本
    该问题已在Hibernate 5.6.15及后续版本修复,可直接升级Spring Boot到2.7.8及以上(对应Hibernate 5.6.15+),或单独指定Hibernate版本:

    <!-- Maven依赖示例 -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.6.15.Final</version>
    </dependency>
    

内容的提问来源于stack exchange,提问作者Brian Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:55:18