簡體   English   中英

級聯刪除具有父子關系的對象到同一表的麻煩

[英]Troubles with cascade deleting objects with parent-child relations to the same table

首先,對不起我的英語。

因此,我正在使用休眠的MS SQL Server,但遇到了問題。 我的數據庫中有一個表的下一個映射:

    @Entity(name = " ... ")
    public class Entity extends BaseEntity implements Comparable {
        @Id
        @Column(name = "...")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;

        @Column(name = "parent_entity_id", insertable = false, updatable = false)
        private Integer parentId;

        @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST})
        @JoinColumn(name = "parent_entity_id")
        private Entity parent;

        @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = {CascadeType.REMOVE}, orphanRemoval = true)
        private Set<Entity> children;
    //other fields, setters, getters
}

這意味着,我的Entity對象可以具有子對象,它們也是Entity對象。

因此,我的問題是我無法正確刪除父母及其所有子女。 當我嘗試刪除父項時,出現SQL錯誤:

The DELETE statement conflicted with the SAME TABLE REFERENCE

那么,有什么想法,如何解決這個問題呢?

您有一個在parent_entity_id和id之間定義的外鍵。 將其設置為允許級聯刪除:刪除父級將刪除其所有子級,以及所有其子級等。

確保您確實希望這種情況發生!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM