我试图创建一个表,捕获父子关系,如树。我想只保留两列来捕获这个结构"id"one_answers"parent"。我希望数据库能够在删除一行时级联删除所有子行。下面是我创建的Hibernate实体,我添加了注释@OnDelete(action = OnDeleteAction.CASCADE)
,但是,当Hibernate创建表时,ON DELETE CASCADE
没有添加到表中。
这是一个bug吗?还是我错过了什么或者不理解什么?
@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;
}
}
@OnDelete
应在@OneToMany
侧使用:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent")
@OnDelete(action = OnDeleteAction.CASCADE)
private List<Tree> children;
你还错过了mappedBy
-它在双向关系中是必需的