OnDelete级联同一个表

OnDelete级联同一个表

本文介绍了Hibernate @OnDelete级联同一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个表来捕获父子关系,例如一棵树.我只想维护两列以捕获此结构"id"和"parent".我希望数据库能够在删除行时级联删除所有子级.下面是我创建的Hibernate实体,我添加了注释@OnDelete(action = OnDeleteAction.CASCADE),但是当Hibernate创建表时,ON DELETE CASCADE不会添加到表中.

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;
    }
}

推荐答案

@OnDelete应该在@OneToMany侧使用:

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

您还错过了mappedBy-双向关系中是必需的.

Also you missed mappedBy - it's required in bidirectional relationships.

这篇关于Hibernate @OnDelete级联同一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:32