首页 > 解决方案 > Hibernate 生成的 id 导致错误消息:“密钥已存在”

问题描述

我正在使用带有 hibernate 和 postgres 的 spring 应用程序来存储数据。产品实体的配置如下:

/**
 * A Product.
 */
@Entity
@Table(name = "product")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "product")
public class Product implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    ...

}

当我想使用 Web 应用程序创建产品时,出现以下错误duplicate key value violates unique constraint. Detail : the key (id)=(35018) already exists

据我了解,hibernate 使用 db 中的序列来生成下一个 id 值。所以我SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';在 psql shell 中获取了我的数据库中的所有序列。输出是:

hibernate_sequence
 jhi_user_id_seq
 key_value_id_seq
 jhi_persistent_audit_event_event_id_seq
 unit_id_seq
 generic_user_id_seq
 currency_id_seq
 customer_type_id_seq
 customer_exploitation_type_id_seq
 legal_entity_id_seq
 deposit_id_seq
 machine_id_seq
 tank_id_seq
 address_id_seq
 product_id_seq
 rewarded_file_id_seq
 bar_code_type_id_seq
 quality_label_id_seq
 shop_pdv_id_seq
 brand_id_seq
 category_id_seq
 material_id_seq
 ws_call_id_seq
 postal_code_id_seq
 commune_id_seq
 country_id_seq
 event_id_seq
 event_type_id_seq
 key_blob_id_seq
 card_id_seq

所以我觉得很好,我有一个 product_id_seq,我只需要更新它的值就可以工作。但是当我请求价值时,SELECT * FROM product_id_seq;我得到:

 last_value | log_cnt | is_called
------------+---------+-----------
     100616 |       0 | t

所以在这里我认为为产品 id 生成的 id 不是来自这个product_id_sequence,因为它试图插入一个 id = 的产品,35018最后product_id_seq一个值为100616.

所以我想知道这个 id 35018 是从哪里来的?使用哪个序列来生成它?我的猜测是我必须更新这个神秘的序列才能让事情正常进行。有关信息,休眠序列的值为36400.

有什么想法可以让我继续前进吗?提前致谢。

标签: springpostgresqlhibernate

解决方案


您不会将您的序列与 postgre 序列映射,因此 Hibernate 会为自己创建序列hibernate_sequence(您从中获得的序列35018)。

要使用现有序列:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator",  sequenceName = "product_id_seq")
private Long id;

推荐阅读