Hibernate @OnDelete 级联同表
我正在尝试创建一个捕获父子关系的表,就像一棵树一样。我想只维护两列来捕获这个结构“id”和“parent”。我希望数据库能够在删除一行时级联删除所有子级。下面是我创建的 Hibernate 实体,我添加了注释 @OnDelete(action = OnDeleteAction.CASCADE)
但是,ON DELETE CASCADE
未添加到表中当 Hibernate 创建表时。
这是一个错误吗?或者有什么我遗漏或不理解的地方?
@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;
}
}
I am trying to create a table which captures parent child relationships, like a tree. I would like to maintain only two columns to capture this structure "id" and "parent". I want the database to be able to cascade delete all children when a row is deleted. Below is the Hibernate Entity that I have created, I have added the annotation @OnDelete(action = OnDeleteAction.CASCADE)
however, the ON DELETE CASCADE
is not added to the table when the table is created by Hibernate.
Is this a bug? Or is there something I am missing or not understanding?
@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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@OnDelete
应该在@OneToMany
端使用:您还错过了
mappedBy
- 它在双向关系中是必需的。@OnDelete
should be used at@OneToMany
side:Also you missed
mappedBy
- it's required in bidirectional relationships.