首页 > 解决方案 > 使用 JPA 在 Spring Boot 中生成的序列 ID(来自 DB 序列)由其他服务器/实例共享并导致违反唯一约束

问题描述

我们正在为应用程序中的关键模块开发新的 API 服务并使用 Spring boot 和 JPA 在这里我们需要您的支持,因为我们面临一个关于 JPA 框架生成的序列的问题 生成的序列 ID 由其他服务器/实例并行共享并导致唯一约束违反

您能否就此提供任何建议以找到其根本原因,以下是我们在实体定义中使用的注释。

使用的注释是

@Id
@SequenceGenerator(name = "POT_PO_HEADER_S1", sequenceName = "POT_PO_HEADER_S1", allocationSize=1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "POT_PO_HEADER_S1")
@Column(name="POH_ID", unique=true, nullable=false, precision=22)
private Long pohId;

日志是

 select
        pot_po_header_s1.nextval 
    from
        dual
2020-Feb-06 11:18:30.808 DEBUG [http-nio-8060-exec-1] o.h.i.e.SequenceStructure - Sequence value obtained: 14021954

 2020-Feb-06 11:18:32.019 DEBUG [http-nio-8060-exec-1] o.hibernate.SQL - 
    insert 
    into
        pot_po_header
        (dept_code, dist_center, po_number, pot_cust_id, source_id, source_table, create_user, modify_user, create_user_name, modify_user_name, poh_id) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2020-Feb-06 11:18:32.673 DEBUG [http-nio-8060-exec-1] o.h.e.j.s.SqlExceptionHelper - could not execute statement [n/a]
java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (TNT_OWNER.POT_PO_HEADER_PK) violated

标签: javaspringhibernatespring-bootjpa

解决方案


我不确定您如何获得您的序列 ID,该序列 ID 在您的日志中打印如下

2020-Feb-06 11:18:30.808 DEBUG [http-nio-8060-exec-1] o.h.i.e.SequenceStructure - Sequence value obtained: 14021954

保存实体后,您将获得序列值,如下所示

Entityr e = epository.save(entity); 那么您可以将自动生成的值pohId设为 as e.getPohId


推荐阅读