Hibernate JPA 为主键提供重复条目,同时在数据库中手动执行 sql 后保存新对象

问题描述 投票:0回答:1

我使用 JPA 进行 mysql 操作,但是在数据库中进行一些手动操作(例如插入、删除、转储等)后,当使用

Repository.save(entityModel)
保存实体时。我收到此错误 -

Duplicate entry 'x' for key 'xxxxx.PRIMARY'

我的主键实体是这个

@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE )
protected Long id;
mysql spring-boot hibernate jpa primary-key
1个回答
0
投票

GenerationType.SEQUENCE 维护一个表,即类似于entity_seq,它具有 next_val 列,从该列获取下一行插入到entity_table 中的值。 enter image description here 您已手动插入数据,这意味着您已将序列表留在实体表后面。只需将序列表中的next_val修改为原数据表的(latest_id+1)即可解决此错误。

© www.soinside.com 2019 - 2024. All rights reserved.