我的一对多映射存在问题
两个表问题(PK(id),文本)和答案(PK(id,questionId),文本)
在我的应用程序中,我以只读模式使用此表
我想要定义这些表之间的关系
@Entity
@Table(name = "QUESTIONS")
public class Question {
@Id
@Column(name = "QUESTIONID")
private long questionId;
@Column(name = "QUESTIONTEXT")
private String questionText;
@OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
private List<Answer> answers;
}
@Entity
@Table(name = "ANSWERS")
public class Answer implements Serializable {
@EmbeddedId
private AnswerPK AnswerPK;
@Column(name = "ANSWERTEXT")
private String answerText;
@ManyToOne
@JoinColumn(name = "QUESTIONID", insertable = false, updatable = false)
private Question question;
}
@Embeddable
public class AnswerPK implements Serializable {
@Column(name = "QUESTIONID")
private long questionId;
@Column(name = "ANSWERID")
private int answerId;
}
但是当我使用@JoinColumn时会创建外键。
当我尝试填充表格时,我得到了异常
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (ZODI.FK_ANSWERS_QUESTIONID) violated - child record found
答案 0 :(得分:1)
尝试将insertable / updatable = false放入EmbeddedId,而不是JoinColumn。
另外考虑不使用EmbeddedId,而是使用IdClass,然后您只需要使用@Id注释answerId和问题。或者甚至更好,从主键中删除questionId并确保answerId是唯一的(例如使其成为生成的id)。