2

我正在尝试创建一个捕获父子关系的表,例如一棵树。我想只保留两列来捕获这个结构“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;
    }
}
4

1 回答 1

5

@OnDelete应该在@OneToMany旁边使用:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent")
@OnDelete(action = OnDeleteAction.CASCADE) 
private List<Tree> children; 

你也错过了mappedBy- 它是双向关系所必需的。

于 2011-11-21T10:53:58.410 回答