I have the following table structure The Model Classes are :
@Entity
public class Choice {
@Id
@GeneratedValue
@Column(name="CHOICE_ID")
private Long id;
@Column(nullable=false)
private String text;
}
@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 both a One-to-Many relationship between question and choices. And a One to One relationship between Question and Right Choice. It would be better if both the relationships are unidirectional.
It would be helpful if someone could give a better table desgin.
I think that you do not need a RightChoice entity, because you can have a boolean inside your Choice entity.
@Table("CHOICE")
@Entity
class Choice {
<....>
@Column(name = "CORRECT")
private Boolean correct = false;
<....>
private Boolean getCorrect(){
return correct;
}
}
And when you will construct a question, before add to question list, set one of choices 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 should use OneToMany(cascade = CascadeType.PERSIST)
inside your Question entity. This means that the persistence will propagate (cascade) EntityManager operation PERSIST to the relating entities.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.