Reputation: 423
in a Java project + spring, i have these two class and a code to insert data:
@Entity(name = "Quiz")
@Table(name = "quiz")
@PrimaryKeyJoinColumn(name="id")
public class Quiz implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy="quiz", fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private List<QuizQuestion> quizQuestions= new ArrayList<>();
@Entity(name = "QuizQuestion")
@Table(name = "quiz_question")
@PrimaryKeyJoinColumn(name="id")
public class QuizQuestion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String text;
@ManyToOne
@JoinColumn(name = "quiz_id", referencedColumnName="id")
private Quiz quiz;
Quiz javaQuiz= new Quiz();
javaQuiz.setName("QCM Java");
QuizQuestion qOne= new QuizQuestion();
qOne.setText("where");
List<QuizQuestion> listQJava= new ArrayList<>();
listQJava.add(qOne);
javaQuiz.setQuizQuestions(listQJava);
quizDao.save(javaQuiz);
by recording a quiz, I have in the table "quiz_question" the column quiz_id which is always NULL
Thank you for your help!
Upvotes: 0
Views: 133
Reputation: 1945
Generally, @JoinColumn indicates that the entity is the owner of the relationship & mappedBy indicates that the entity is the inverse of the relationship.
So, if you are trying like following
@OneToMany(mappedBy="quiz", fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private List<QuizQuestion> quizQuestions= new ArrayList<>();
That means it is inverse of the relationship and it will not set parent reference to its child.
To set parent reference to its child, you have to make the above entity owner of the relationship in the following way.
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn
private List<QuizQuestion> quizQuestions= new ArrayList<>();
You need not set any child reference because above code will create a column in the child table.
Upvotes: 1