在我的 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,但该值不起作用,因为它已经存在。
MMTTMM
相关分类