问题描述
我对父实体和子实体之间的简单 @OneToMany
映射有问题.一切正常,只是当我从集合中删除它们时不会删除子记录.
I have a problem with a simple @OneToMany
mapping between a parent and a child entity. All works well, only that child records are not deleted when I remove them from the collection.
家长:
@Entity
public class Parent {
@Id
@Column(name = "ID")
private Long id;
@OneToMany(cascade = {CascadeType.ALL}, mappedBy = "parent")
private Set<Child> childs = new HashSet<Child>();
...
}
孩子:
@Entity
public class Child {
@Id
@Column(name = "ID")
private Long id;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="PARENTID", nullable = false)
private Parent parent;
...
}
如果我现在从 childs Set 中删除和 child,它不会从数据库中删除.我尝试取消 child.parent
引用,但这也不起作用.
If I now delete and child from the childs Set, it does not get deleted from the database. I tried nullifying the child.parent
reference, but that did not work either.
实体在 Web 应用程序中使用,删除作为 Ajax 请求的一部分发生.按下保存按钮时,我没有已删除子项的列表,因此我无法隐式删除它们.
The entities are used in a web application, the delete happens as part of an Ajax request. I don't have a list of deleted childs when the save button is pressed, so I can't delete them implicitly.
推荐答案
JPA 的行为是正确的(意味着按照规范):对象不会被删除,因为您已将它们从一对多集合.有一些特定于供应商的扩展可以做到这一点,但原生 JPA 不能满足它.
JPA's behaviour is correct (meaning as per the specification): objects aren't deleted simply because you've removed them from a OneToMany collection. There are vendor-specific extensions that do that but native JPA doesn't cater for it.
部分原因是 JPA 实际上并不知道它是否应该删除从集合中删除的某些内容.在对象建模方面,这是组合和聚合*"之间的区别.
In part this is because JPA doesn't actually know if it should delete something removed from the collection. In object modeling terms, this is the difference between composition and "aggregation*.
在组合中,没有父实体,子实体就不存在.一个经典的例子是在 House 和 Room 之间.删除房子和房间.
In composition, the child entity has no existence without the parent. A classic example is between House and Room. Delete the House and the Rooms go too.
聚合是一种松散的关联,以课程和学生为代表.删除课程,学生仍然存在(可能在其他课程中).
Aggregation is a looser kind of association and is typified by Course and Student. Delete the Course and the Student still exists (probably in other Courses).
因此,您需要使用特定于供应商的扩展来强制执行此行为(如果可用)或明确删除子项并将其从父项的集合中删除.
So you need to either use vendor-specific extensions to force this behaviour (if available) or explicitly delete the child AND remove it from the parent's collection.
我知道:
- 休眠:级联delete_orphan.参见 10.11.传递持久性;和
- EclipseLink:称之为私有制".请参阅如何使用@PrivateOwned 注解.莉>
- Hibernate: cascade delete_orphan. See 10.11. Transitive persistence; and
- EclipseLink: calls this "private ownership". See How to Use the @PrivateOwned Annotation.
这篇关于JPA OneToMany 不删除子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!