[英]Hibernate many-to-many mapping to the same entity unidirectional
我有代表樹節點類型的表。 下面的映射說明了節點的多對多映射。
@Entity
public class Node {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany
@JoinTable(name = "node_dependency",
joinColumns = {@JoinColumn(name = "parent_id")},
inverseJoinColumns = {@JoinColumn(name = "child_id")})
private List<Node> childNodes = new ArrayList<>();
}
它有效,但我想有單獨的表映射以簡化刪除查詢。
@Entity
public class NodeRelation {
@ManyToOne
private Node parent;
@ManyToOne
private Node child;
}
如果我有 NodeRelation,我可以很容易地找到在樹的不同層上重復使用的節點,並且不能安全地刪除,這更難做到而不是(節點上的一對多 + FK 上的多對一) NodeRelation) 僅多對多映射。
我嘗試了用 NodeRelation 表示的復合鍵映射的不同組合,但沒有運氣(根據 db 模式的驗證沒有通過)。 請建議我在這個用例中哪個映射更好。
最好不要在Node
使用childNodes
關聯。
將id
添加到NodeRelation
會很方便。
@Entity
public class Node {
@Id
@GeneratedValue
private Long id;
}
@Entity
public class NodeRelation {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Node parent;
@ManyToOne
private Node child;
}
您還可以向NodeRelation
添加唯一約束(parent, child)
(具有與@ManyToMany
連接表相同的行為)。
它只需要對NodeRelation
表進行查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.