如何设置子元素的父ID?

时间:2015-12-27 19:30:11

标签: java hibernate

我正在开发一个调查创建者应用程序。

Survey.java

@Table(name = "SURVEYS")
@Entity
public class Survey implements Serializable{
.
.
.
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "genSurvey")
    @SequenceGenerator(name = "genSurvey", sequenceName = "SEQ_SURVEY", allocationSize = 1)
    private Long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "surveyId")
    private Set<Question> questions = new HashSet<Question>();
.
.
.
}

Question.java

@Table(name = "QUESTIONS")
@Entity
public class Question implements Serializable{
.
.
.
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "genSurveyQuestions")
    @SequenceGenerator(name = "genSurveyQuestions", sequenceName = "SEQ_SURVEY_QUESTIONS", allocationSize = 1)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "SURVEY_ID")
    private Survey surveyId;
.
.
.
}

在为调查添加新问题时,我使用以下代码:

Test.java

survey.getQuestion().add(question1);
survey.getQuestion().add(question2);

currentSession.saveOrUpdate(survey);

运行此代码后,我希望它能够持续存在调查和问题。但我得到以下错误:

  

org.hibernate.exception.ConstraintViolationException:ORA-01400:   无法插入NULL(“QUESTIONS”。“SURVEY_ID”)

     

引起:java.sql.SQLException:ORA-01400:无法插入NULL   ( “问题”。 “SURVEY_ID”)

不知何故,它将问题'surveyIds设置为null。我的OneToMany协会出了什么问题,我无法弄明白。任何有用的帮助。

注意: 我使用以下链接作为参考: http://fruzenshtein.com/bidirectional-many-to-one-association/

2 个答案:

答案 0 :(得分:1)

如果情况并非如此,您还需要在致电question.setSurvey(survey)之前致电saveOrUpdate(survey)所有问题。

通常我们在Survey class:

上定义这样的方法
public void addQuestion(Question q) {
    q.setSurvey(this);
    questions.add(q);
}

答案 1 :(得分:0)

您应该在集合上使用获取类型EAGER,以便在调用saveOrUpdate之前从会话中获取所有依赖项。

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "surveyId")