简体   繁体   English

JPA CascadeType.ALL 不删除子记录

[英]JPA CascadeType.ALL not deleting child records

Consider this use case.考虑这个用例。

class Category {
   @OneToMany(cascade=CascadeType.ALL)
   List<Application> applications = new ArrayList<Application>();
}

class Application {
   @ManyToOne
   Category category;       
}

I understand that, On this case, when category will be deleted, application will also be deleted.我理解,在这种情况下,当类别被删除时,应用程序也将被删除。 But who takes care of join table?但是谁负责连接表? The Category_Application table generated for the relation.为关系生成的 Category_Application 表。

The join table rows should always be deleted, regardless of cascade .无论cascade是什么,都应始终删除连接表行。

For a bi-directional ManyToMany to owning (non- mappedBy ) side will delete the rows.对于拥有(非mappedBy )方的双向ManyToMany将删除行。

Since you have a ManyToOne back, it seems you should be using a mappedBy , not a join table.既然你有一个ManyToOne回来,你似乎应该使用mappedBy ,而不是连接表。

Is the issue that they are not being deleted, or are you getting a constraint error before they are deleted?是它们没有被删除的问题,还是在它们被删除之前出现约束错误? Also ensure you collection is not empty when you call remove() .还要确保您在调用remove()时集合不为空。 Try also removing everything from the collection before calling remove .尝试在调用remove之前从集合中删除所有内容。

It sounds like this is the same issue as:听起来这与以下问题相同:

JPA CascadeType.ALL does not delete orphans JPA CascadeType.ALL 不删除孤儿

Basically, when you have a @OneToMany , JPA assumes by default that the child object has an independent lifecycle and may be associated to multiple parents.基本上,当您有@OneToMany时, JPA 默认假定子 object 具有独立的生命周期,并且可能与多个父级相关联。 Deleting the parent does not necessarily delete the child.删除父级并不一定会删除子级。 Specifying orphanRemoval=true in JPA 2.0 (or Eclipselink @PrivateOwned or Hibernate CascadeType.DELETE_ORPHAN ) tells JPA to remove the child records when the parent is deleted.在 JPA 2.0(或 Eclipselink @PrivateOwned或 Hibernate CascadeType.DELETE_ORPHAN )中指定orphanRemoval=true会告诉 Z9CE3D1BD8890F16A0C4480935 删除父记录时删除子记录。

If you always want to tie the child record lifecyle to its parent, you might also want to consider @ElementCollection instead of @OneToMany, which will give similar behavior but not let you persist child objects independently of the parent.如果您总是想将子记录生命周期绑定到其父记录,您可能还需要考虑使用@ElementCollection 而不是@OneToMany,这将提供类似的行为,但不允许您独立于父对象保留子对象。 (ie, the child objects of an @ElementCollection are not @Entities.) (即,@ElementCollection 的子对象不是@Entities。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM