在我的 Spring Boot 應用程序中,我試圖保存一個具有一些具有一對多關系的嵌套實體的實體。我使用 JPA 和 Hibernate 將它們保存到 MySQL 數據庫。在主鍵上,我使用@GeneratedValue(strategy = GenerationType.AUTO)onLong自動為新實體創建值。這工作了一段時間,但是最近我在嘗試保存實體時遇到錯誤:java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '282' for key 'PRIMARY'這就是我的實體的樣子:Question.java@Entity@Table(name = "question")public class Question { private Long id; private List<Answer> answers; // other fields @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @OneToMany(mappedBy = "question", cascade = CascadeType.ALL, orphanRemoval = true) public List<Answer> getAnswers() { return answers; } public void setAnswers(List<Answer> answers) { this.answers = answers; }}Answer.java@Entity@Table(name = "answer")public class Answer { private Long id; private Question question; // other fields @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @ManyToOne @JoinColumn(name = "question_id") public Question getQuestion() { return question; } public void setQuestion(Question question) { this.question = question; }}存儲庫很簡單:public interface QuestionRepository extends JpaRepository<Question, Long>{ ... }現在假設我通過 Web 表單添加一個新問題,包括 4 個答案。當調用存儲庫時,就像:questionRepository.save(question);經過一番調查后,Hibernate 似乎正在使用question實體表中的自動增量值answers,但該值不起作用,因為它已經存在。
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
由于 MySQL 本身不支持序列,因此使用 @GenerateValue(strategy = GenerationType.AUTO) 時可能會出現此問題。
使用以下解決方法來生成 id。
@Id@GeneratedValue( ????strategy=?GenerationType.AUTO, ????generator="native" ) @GenericGenerator( ????name?=?"native", ????strategy?=?"native" )
添加回答
舉報
0/150
提交
取消