首页 > 解决方案 > 内部带有 OneToOne 的 ElementCollection 不会级联“删除”

问题描述

我的模型设置如下:

@Table(name = "parent")
@Entity
public class Parent extends IdEntity {

  @ElementCollection(fetch = EAGER)
  @CollectionTable(
          name = "foo",
          joinColumns = @JoinColumn(name = "parent_id")
  )
  private List<Foo> foos = new ArrayList<>();
}

@Embeddable
public class Foo {

    @NotNull
    @OneToOne(optional = false, cascade = ALL)
    private Bar bar;
}

@Entity
public class Bar extends IdEntity {

    private String baz; // marked as unique in the DB
}

Parent实例的每次更新时,我都会收到一个异常,说有一个重复的Bar→baz条目。

org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [bar.baz]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

我手动清理foos集合并在每次更新时重新输入条目addAllFoo

我的理解是,由于 的性质ElementCollection,它级联所有操作并删除孤儿。由于我有一个cascade = ALLon Foo→barthen 这应该意味着所有这些条目也将被删除和读取。那么可能导致“重复输入”错误的原因是什么?

标签: jpaspring-data-jpa

解决方案


推荐阅读