I have problem with one-to-many mapping.
Two tables questions(PK(id), text) and answers(PK(id, questionId), text)
In my app I use this tables in read-only mode.
I want define relations between this tables
@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;
}
But when I use @JoinColumn will be created foreign key.
And when I try to fill tables, I got exception
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (ZODI.FK_ANSWERS_QUESTIONID) violated - child record found
Try putting the insertable/updatable=false in the EmbeddedId, not the JoinColumn.
Also consider not using an EmbeddedId, instead use a IdClass, then you just need to annotate the answerId and the question with @Id. Or even better, remove the questionId from the primary key and ensure answerId is unique (such as making it a generated id).
See,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships