从@ OneToMany-association中删除子项:CascadeType.ALL + orphanRemoval = true not working

时间:2012-05-03 07:30:18

标签: java hibernate jpa-2.0

我很难从OneToMany-association中删除孩子。我的实体:

@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;
  ...

我未能成功删除孩子:

personEntity.getProjects().clear();

这有效,但我不认为这是正确的方法:

for (Iterator<ProjectEntity> iterator = personEntity.getProjects().iterator(); iterator.hasNext();)
{
  ProjectEntity projectEntity = iterator.next();
  projectDao.deleteEntity(projectEntity);
  iterator.remove();
}

我在这里做错了什么?

感谢
强尼

1 个答案:

答案 0 :(得分:14)

关联是双向的,双向关联的拥有方是没有mappedBy属性的关联。这意味着在这种情况下,拥有方是项目方。

Hibernate只考虑拥有方知道关联是否存在。这意味着要破坏人员和项目之间的关联,您必须将人员设置为项目中的null