試圖在Hibernate中實現繼承。Hibernate繼承,父類應該是基於決定者的子類或父類
以下是架構
這裏是什麼類是,
//Grand Parent Class
@Entity
@Table(name="grand_parent")
public class GrandParent{//consider @id}
//Parent Class
@Entity
@Table(name = "parent")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "decider", discriminatorType = DiscriminatorType.STRING)
public class Parent{//consider @id}
//ChildX class
@Entity
@Table(name = "childX")
@PrimaryKeyJoinColumn(name="id")
@DiscriminatorValue("X")
public class ChildX() extends Parent{//consider value}
//ChildY class
@Entity
@Table(name = "childY")
@PrimaryKeyJoinColumn(name="id")
@DiscriminatorValue("Y")
public class ChildY extends Parent(//consider value){}
//ChildZ class
@Entity
@Table(name = "childZ")
@PrimaryKeyJoinColumn(name="id")
@DiscriminatorValue("Z")
public class ChildZ() extends Parent{//consider value}
使用案例:
- 如果判定爲 'K',和4記錄需要保存,那麼4個父記錄應該是a dded
- 如果決定者是'X/Y/Z',並且需要保存4條記錄,那麼應該添加1條父記錄和4條ChildX/ChildY/ChildZ記錄。
然而,父表應該被視爲一個孩子時,決勝局是「K」,當判定爲「X/Y/Z」
但它必須充當父上面的類圖中,每當決策者爲'X/Y/Z'時,4個記錄保存在ChildX/ChildY/ChildZ中,父表中沒有記錄。
另外如何檢索上面的記錄。
EDITS
@Entity
@Table(name="grand_parent")
public class GrandParent{
@OneToMany(mappedBy = "parentRecord",
fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
@Cascade(org.hibernate.annotations.CascadeType.DELETE)
private List<parent> parentList;
}
//Parent Class
@Entity
@Table(name = "parent")
public class Parent{
@ManyToOne()
@JoinColumn(name = "fk_gp_id")
private GrandParent parentRecord;
@OneToMany(mappedBy = "childrecord",
fetch = FetchType.LAZY,
cascade = CascadeType.ALL)
@Cascade(org.hibernate.annotations.CascadeType.DELETE)
private List<Child> childList;
}
@Entity
@DiscriminatorColumn(name = "decider", discriminatorType = DiscriminatorType.STRING)
public abstract class Child(){
@ManyToOne(optional = false)
@JoinColumn(name = "fk_parent_id")
private parent childrecord;
}
//ChildX class
@Entity
@Table(name = "childX")
@DiscriminatorValue("X")
public class ChildX() extends Parent{//consider value}
......
要添加..
GrandParent gp = new GrandParent();
Parent p = new Parent();
ChildX ch = new ChildX();
ch.setChildrecord(p);
p.setChildList(//Array added ch);
p.setParentRecord(gp);
gp.setParentList(//Array added p);
persist(gp);
現在我得到一個錯誤:
Application error : com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'Child' doesn't exist
孩子們不應該延長家長嗎?如果'''Parent'''不能獨立存在,你應該把它抽象出來。 –
更新了我的任務。是孩子延伸父母 –