Jpa:存储由Entity组成的Value对象的集合

时间:2012-10-07 18:00:18

标签: hibernate jpa orm

@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类的注释?

感谢。

1 个答案:

答案 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);
 }