2013-04-09 197 views
4

編輯:修改問題以更好地反映問題。最初發布問題hereJPA:級聯刪除不刪除子

我有一個父母(Context)和一個孩子(User)實體(ManyToOne關係)。在父級上級聯'刪除'不會刪除子級。代碼如下:

//Owning side - child 
@Entity 
public class User { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private int id; 
    @Column(name = DBColumns.USER_NAME) 
    private String name; 
    @ManyToOne 
    @JoinColumn(name = DBColumns.CONTEXT_ID) 
    private Context context; 
} 

//parent 
@Entity 
public class Context { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private int id; 
    @Column(name = DBColumns.CONTEXT_NAME) 
    private String name; 
    @OneToMany(mappedBy = "context", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true) 
    private Set<User> users = new HashSet<User>(); 
} 

//usage 
Context sampleContext = new Context("sampleContext"); 
em.persist(sampleContext); 
User sampleUser = new User(sampleContext, "sampleUser"); 
em.persist(sampleUser); 
em.remove(sampleContext); //should remove user as well but throws foreign key dependency error 
+0

。如果指定orphanRemoval = true,則不需要添加CascadeType.REMOVE。 (參見JSR338,第2.9節) – 8hZWKA 2016-10-08 10:54:54

回答

3

我需要刪除之前刷新實體:

em.refresh(sampleContext); 
em.remove(sampleContext); 

早些時候,實體被刪除(sampleContext)不知道sampleUser與之相關聯(可能是因爲sampleContext正從高速緩存中取出)。在delete之前執行refresh可確保實體從數據庫更新。順便說一句,

0

不要將您的關係表映射爲en實體。使用@ManyToMany而是讓你的用戶實體擁有關係。

編輯:

因此您的關聯表的主鍵必須由外國鍵。

看到這個http://giannigar.wordpress.com/2009/09/04/mapping-a-many-to-many-join-table-with-extra-column-using-jpa/

+0

我想保持它的獨立性,以便在稍後的時間點,我可以使用字符串而不是直接實體來指定映射(以促進正則表達式)。例如,我想通過映射'user:role :: *:employee'來說「All'users'屬於'employee'角色」。 – Neo 2013-04-10 05:36:20

+0

@Venkatesh:查看編輯 – Gab 2013-04-10 06:53:59

+0

感謝您的鏈接。這是信息。但是,我也遇到了ManyToOne關係的問題。編輯問題以使問題更清楚。 – Neo 2013-04-10 12:07:43

1

你調用remove()上sampleUser不sampleContext,和用戶沒有級聯刪除對語境,所以你應該只看到用戶被刪除。

如果在sampleContext上調用remove(),則還必須確保在創建用戶時將用戶添加到上下文的用戶。你很可能只設置用戶的conext。

+0

更正了錯字。它必須是'remove(sampleContext)'。 – Neo 2013-04-12 07:11:37

+0

該解決方案有效。但是,沒有必要手動將'User'添加到'Context'的用戶。 JPA自己做。我只需要刷新'Context'然後將其刪除(以便其用戶現在可以從數據庫更新) – Neo 2013-04-12 07:15:17