Pregunta

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;
    }
}
¿Fue útil?

Solución

@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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top