![](/img/trans.png)
[英]JPA / Hibernate unidirectional one-to-one mapping with shared primary key
[英]Hibernate One-to-One Unidirectional mapping using join table
我有以下表格結構 模型類是:
@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;
}
使用注釋我希望在問題和選擇之間建立一對多的關系。 問題與權利選擇之間的一對一關系。 如果兩種關系都是單向的,那就更好了。
如果有人能提供更好的表格設置會很有幫助。
我認為你不需要RightChoice實體,因為你可以在Choice實體中有一個布爾值。
@Table("CHOICE")
@Entity
class Choice {
<....>
@Column(name = "CORRECT")
private Boolean correct = false;
<....>
private Boolean getCorrect(){
return correct;
}
}
當你構建一個問題時,在添加到問題列表之前,將其中一個選項設置為correct = true;
Choice choice = new Choice();
choice.setCorrect(true);
*<other choices are ommited intentionally>*
question.add(choice);
*<other adds are ommited intentionally>*
您還應該在Question實體中使用OneToMany(cascade = CascadeType.PERSIST)
。 這意味着持久性將EntityManager操作PERSIST傳播(級聯)到相關實體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.