Kutluhan Metin
Kutluhan Metin

Reputation: 59

How to set parent id of child element?

I am developing a survey creator application.

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;
.
.
.
}

while adding a new question to a survey I use following code:

Test.java

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

currentSession.saveOrUpdate(survey);

After running this code I expect it should persist survey and questions. But I get the following errors:

org.hibernate.exception.ConstraintViolationException: ORA-01400: cannot insert NULL into ("QUESTIONS"."SURVEY_ID")

Caused by: java.sql.SQLException: ORA-01400: cannot insert NULL into ("QUESTIONS"."SURVEY_ID")

Somehow it sets questions' surveyIds to null. What's wrong with my OneToMany association, I couldn't figure out. Any help appriciated.

Note: I used the following link as a reference: http://fruzenshtein.com/bidirectional-many-to-one-association/

Upvotes: 1

Views: 972

Answers (2)

Ga&#235;l J
Ga&#235;l J

Reputation: 15275

You also need to call question.setSurvey(survey) on all the questions before calling saveOrUpdate(survey) if it's not the case.

Usually we define a method like this on Survey class:

public void addQuestion(Question q) {
    q.setSurvey(this);
    questions.add(q);
}

Upvotes: 1

Roman C
Roman C

Reputation: 1

You should use fetch type EAGER on the collection to get all depenencies from session before saveOrUpdate is called.

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

Upvotes: 0

Related Questions