Hibernate One-to-One Unidirectional mapping using join table
I have the following table structure Model Classes:
Selection class
@Entity
public class Choice {
@Id
@GeneratedValue
@Column(name="CHOICE_ID")
private Long id;
@Column(nullable=false)
private String text;
}
Question class
@Entity
public class Question {
@Id
@GeneratedValue
@Column(name="QUESTION_ID")
private Long id;
private String text;
@Column(name="CAT_ID")
private Long catId = 1l;
@Column(nullable=false)
private int difficulty;
@Column(nullable=false)
private int set;
@OneToMany
@JoinColumn(name="QUESTION_ID", referencedColumnName="QUESTION_ID")
private List<Choice> choices;
@OneToOne
@JoinTable(name = "RIGHT_CHOICE", joinColumns = { @JoinColumn(name = "QUESTION_ID", referencedColumnName = "QUESTION_ID") })
private Choice rightChoice;
}
Using annotations, I would like to have a one-to-many relationship between question and choice. And a one-to-one relationship between the question and the right choice. It would be better if both relationships were unidirectional.
It would be helpful if someone could provide a better desgin table.
source to share
I think you don't need the RightChoice entity because you can have boolean inside your Choice object.
@Table("CHOICE")
@Entity
class Choice {
<....>
@Column(name = "CORRECT")
private Boolean correct = false;
<....>
private Boolean getCorrect(){
return correct;
}
}
And when you build a question, before adding it to the list of questions, set one of the options as correct = true;
Choice choice = new Choice();
choice.setCorrect(true);
*<other choices are ommited intentionally>*
question.add(choice);
*<other adds are ommited intentionally>*
Also, you must use OneToMany(cascade = CascadeType.PERSIST)
inside the Question object. This means that persistence will propagate (cascade) the EntityManager PERSIST operation to related entities.
source to share