1

我想創建一個捕獲父級子關係,如樹的表。我想只維護兩列來捕捉這個結構「id」和「parent」。我希望數據庫能夠在刪除一行時級聯刪除所有子項。下面是我創建的Hibernate實體,我添加了註釋@OnDelete(action = OnDeleteAction.CASCADE)但是,當表由Hibernate創建時,不會將ON DELETE CASCADE添加到表中。休眠@OnDelete級聯相同的表

這是一個錯誤?或者是有什麼我失蹤或不理解?

@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; 
    } 
} 
+0

您是否嘗試在@ OneToMany集合上放置'orphanRemoval = true'? (在** @ ManyToOne上**不**)? –

+0

嗨Pitor,我試過了,但「ON DELETE CASCADE」仍然沒有添加到表格中。 –

回答

5

@OnDelete@OneToMany側處:

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

你也錯過了mappedBy - 它需要雙向的關係。

+0

Thany你,那工作!我必須刪除@JoinColum註釋,使其看起來像這樣:@OneToMany(fetch = FetchType.EAGER,mappedBy =「parent」) @OnDelete(action = OnDeleteAction.CASCADE) private List children;' –

+0

@阿里:是的,雙向關係中的@ @ JoinColumn應放在'@ ManyToOne'側。 – axtavt