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

Spring JPA忽略序列表next_val值,ID生成异常求助

问题:MySQL下Spring JPA序列生成ID不生效,始终从1开始

现象

序列表excel_line_seq中next_val的值为20:

select * from excel_line_seq;
+----------+
| next_val |
+----------+
|        20 |
+----------+

但使用Spring JPA Repository保存新实体时,调用save()后实体的id = 1:

var excelLineEntity = new ExcelLineEntity();
excelLineEntity.setFileName("file1.txt");
excelLineEntity = excelLineRepository.save(excelLineEntity);

// 不符合预期,id至少应为20或下一个序列值
Assertions.assertEquals(1, excelLineEntity.getId());

尝试持久化2个实体时,抛出异常:

org.springframework.dao.DuplicateKeyException: A different object with the same identifier value was already associated with the session

原因是Spring JPA Repository为两个独立实体分配了同一个id = 1。

配置情况

JPA实体的ID生成策略定义为strategy = GenerationType.SEQUENCE:

@Entity
@Table(name = "excel_line")
public class ExcelLineEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE)
  Long id;

  String fileName;
}

Spring Data JPA Repository定义:

public interface ExcelLineRepository extends JpaRepository<ExcelLineEntity, Long> {}

由于MySQL不支持原生序列,因此创建了excel_line_seq表并插入值20。

补充信息

  • 数据库schema由Liquibase生成
  • Spring JPA通过spring.jpa.hibernate.ddl-auto=validate验证schema,当序列表不存在时会触发验证错误,说明JPA已识别excel_line_seq为正确的ID生成表
  • 曾尝试显式配置序列,但结果仍一致:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "excelLineSequence")
@SequenceGenerator(name = "excelLineSequence", sequenceName = "excel_line_seq", allocationSize = 50)
Long id;

请问我遗漏了什么?是否必须手动从序列表计算下一个值并设置为实体ID?当前为集成测试场景,不存在应用运行时JPA缓存序列值的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 15:07:06