Removing childs from @OneToMany-association: CascadeType.ALL + orphanRemoval = true not working

≯℡__Kan透↙ 提交于 2020-01-22 09:37:25

问题


I'm having a hard time removing childs from a OneToMany-association. My entities:

@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


回答1:


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.

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.



来源:https://stackoverflow.com/questions/10426979/removing-childs-from-onetomany-association-cascadetype-all-orphanremoval-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!