SpringBoot Version:1.4.2.RELEASE MySQL Version:5.7.16 Lombok
I have two entity classes Question and Options where question_id from Question table is foreign key in Question_Option table.
Question Entity
@Entity
@Table(name = "questions")
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Getter
@Setter
private int questionId;
@Getter
@Setter
@OneToMany(mappedBy = "question",fetch=FetchType.LAZY, cascade=CascadeType.ALL)
private List<Option> option;
Options Entity
@Entity
@Table(name = "questions_options")
public class Option {
@Id
@GeneratedValue
@Getter
@Setter
private int id;
@Getter
@Setter
private String optionsId;
@Getter
@Setter
private String optionText;
@ManyToOne
@JoinColumn(name="questionId")
@Getter
@Setter
private Question question;
}
Problem Statement When I try to POST, foreign key (question_id) is not inserted in options table.
Hibernate: insert into questions (questionId, LastUpdate, active, createTime, questionText, questionType) values (default, ?, ?, ?, ?, ?)
Hibernate: insert into questions_options (id, lastUpdate, optionText, optionsId, questionId) values (default, ?, ?, ?, ?)
Hibernate: insert into questions_options (id, lastUpdate, optionText, optionsId, questionId) values (default, ?, ?, ?, ?)
Hibernate: insert into questions_options (id, lastUpdate, optionText, optionsId, questionId) values (default, ?, ?, ?, ?)
How did I fix this ? I changed Question entity to
@Getter
@Setter
@OneToMany(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name="questionId")
@NotNull
private List<Option> option;
and Options to
@ManyToOne
@Getter
@Setter
@JoinColumn(name="questionId")
private Question question;
But I want to know why first approach is not working and what am I doing wrong.