Hibernate @OnDelete cascade same table

2019-05-20 02:35发布

问题:

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

回答1:

@OnDelete should be used at @OneToMany side:

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

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