@Entity
class Question{
@Id
private int id;
private String questionText;
@OneToMany
Set<AnswerOption> answerOptions;
}
class AnswerOption{
private String option;
@ManyToOne
private Question question;
}
table-columns:
Question: id, text
AnswerOption: question_id, option
example:
Question: Which county are you from?
Possible answers: Kent, Essex, Middlesex, Others
Intended api usage:
Question q = new Question("Which county are you from?");
q.addAnswerOption(new AnswerOption("Kent"))
q.addAnswerOption(new AnswerOption("Essex"))
q.addAnswerOption(new AnswerOption("Middlesex"))
q.addAnswerOption(new AnswerOption("Others"))
questionDao.save(q);
我不需要AnswerOption的标识符,因为我认为AnswerOption是一个Value对象。有人可以推荐如何使用JPA来保持这个模型,因为我不确定用于AnswerOption类的注释?
感谢。
答案 0 :(得分:3)
我想说,让你的AnswerOption
课也作为实体。
@Entity
class AnswerOption{
private String option;
@ManyToOne
private Question question;
}
将oneToMany
类中的Question
映射更改为使用CASCADE
选项,如下所示:
@Entity
class Question{
@Id
private int id;
private String questionText;
@OneToMany(cascade = CascadeType.ALL, mappedBy="question")
Set<AnswerOption> answerOptions;
}
完成后,将问题对象保存如下:
//get your hibernate session
Session session = ....
Question q = new Question("Which county are you from?");
q.addAnswerOption(new AnswerOption("Kent"))
q.addAnswerOption(new AnswerOption("Essex"))
q.addAnswerOption(new AnswerOption("Middlesex"))
q.addAnswerOption(new AnswerOption("Others"))
//use session to save the Question with AnswerOptionss
session.save(q);
确保addAnswerOption
中的Question
方法如下:
public void addAnswerOption(AnswerOption answerOption){
//setting the question as parent in answerOption
answerOption.setQuestion(this).
this.answerOptions.add(answerOption);
}