java 从@OneToMany-association 中删除孩子:CascadeType.ALL + orphanRemoval = true 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10426979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing childs from @OneToMany-association: CascadeType.ALL + orphanRemoval = true not working
提问by user871611
I'm having a hard time removing childs from a OneToMany-association. My entities:
我很难从 OneToMany 关联中删除孩子。我的实体:
@Entity
@Table(name = "PERSON")
public class PersonEntity extends BaseVersionEntity<Long> implements Comparable<PersonEntity>
{
...
// bi-directional many-to-one association to Project
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "person", orphanRemoval = true)
private final Set<ProjectEntity> projects = new HashSet<ProjectEntity>();
...
@Entity
@Table(name = "PROJECT")
public class ProjectEntity extends BaseVersionEntity<ProjectPK>
{
@EmbeddedId
private ProjectPK id;
...
// bi-directional many-to-one association to UdbPerson
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PERSON_ID", nullable = false, insertable = false, updatable = false)
private PersonEntity person;
...
@Embeddable
public class ProjectPK implements Serializable
{
// default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@NotNull
@Column(name = "PERSON_ID")
private Long personId;
...
My unsuccessful attempt to delete the childs:
我删除孩子的失败尝试:
personEntity.getProjects().clear();
This works, but I don't think thats the right approach:
这有效,但我认为这不是正确的方法:
for (Iterator<ProjectEntity> iterator = personEntity.getProjects().iterator(); iterator.hasNext();)
{
ProjectEntity projectEntity = iterator.next();
projectDao.deleteEntity(projectEntity);
iterator.remove();
}
What am I doing wrong here?
我在这里做错了什么?
Thanks
Jonny
谢谢
强尼
回答by JB Nizet
The association is bidirectional, and the owning side of a bidirectional association is the one where there is no mappedBy attribute. This means that in this case, the owning side is the project side.
关联是双向的,双向关联的拥有方是没有mappedBy 属性的一方。这意味着在这种情况下,拥有方是项目方。
Hibernate only considers the owning side to know if the association exists or not. This means that to break the association between a person and a project, you must set the person to null
in the project.
Hibernate 只考虑拥有方知道关联是否存在。这意味着要打破一个人和一个项目之间的关联,你必须null
在项目中设置这个人。