我正在尝试创建一个捕获父子关系的表,就像树一样。我想只保留两列来捕获这个结构“id”和“parent”。我希望数据库能够在删除行时级联删除所有子项。下面是我创建的Hibernate实体,我添加了注释@OnDelete(action = OnDeleteAction.CASCADE)
但是,当Hibernate创建表时,ON DELETE CASCADE
没有添加到表中。
这是一个错误吗?或者有什么我缺少或不理解?
@Entity
public class Tree {
@Id
@Column(name = "id", nullable = false)
private Long id;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "parent", nullable = true)
private List<Tree> children;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
@JoinColumn(name = "parent", nullable = false)
private Tree parent;
public Tree(Long id) {
this.id = id;
}
public Tree() {
}
public Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
public List<Tree> getChildren() {
return children;
}
public void setChildren(List<Tree> children) {
this.children = children;
}
public Tree getParent() {
return parent;
}
public void setParent(Tree parent) {
this.parent = parent;
}
}
答案 0 :(得分:5)
@OnDelete
方使用 @OneToMany
:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent")
@OnDelete(action = OnDeleteAction.CASCADE)
private List<Tree> children;
你也错过了mappedBy
- 这是双向关系所必需的。