JPA:'CascadeType.REMOVE' 或 'orphanRemoval = true',在 n:n 关系中使用 EmbeddeId class 生成新的 table/class?

JPA: 'CascadeType.REMOVE' or 'orphanRemoval = true', which use in a n:n relation that generate new table/class with EmbeddeId class?

我正在为一家比萨店开发 REST API。在这里,我试图删除一个 Flavor 和所有与之相关的数据。下面进一步解释:

类:

考虑到这一点,我们可以得出结论,存在两个多对多关系:

Class diagram of actual implementation

需求是:删除一个Flavor,自动删除所有FillingPositionFlavorFlavorPriceSize

但是,我对 CascadeType.REMOVEorphanRemoval = true 的使用感到困惑:

当我在 Flavor.sizePrices 上使用 Cascade 和 OrphanRemoval 时,在尝试编辑 Flavor 时得到一个 HibernateException,排除工作正常: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.pkg.Flavor.sizePrices

当我在 Flavor.sizePrices 上使用 Cascade 时,在排除 Flavor 时得到 PSQLException,编辑工作正常: ERROR: update or delete on table "tb_flavor" violates foreign key constraint "fk9orw0yhtc0e06ka84dbcd2c82" on table "tb_flavor_size_price"

我正在 Spring 引导中对服务进行单元测试以测试所有 CRUD 操作。

下面是实际代码,为了方便阅读,我隐藏了id等属性。

@Entity
@Table(name = "tb_flavor")
class Flavor {

   @OneToMany(cascade = {CascadeType.PERSIST,CascadeType.REMOVE},orphanRemoval = true)
   private Set<FlavorPositionFilling> flavors = new HashSet<FlavorPositionFilling>();

   @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE},orphanRemoval = true)
   private Set<FlavorPriceSize> priceSizes;

   // other properties and methods
}
@Entity
@Table(name = "tb_flavor_price_size")
class FlavorPriceSize {

   @EmbeddedId
   private FlavorPriceSizeEmbeddeId id;
   private float price;

   // other properties and methods
}

@Embeddable
class FlavorPriceSizeEmbeddeId implements Serializable {
   @ManyToOne(cascade = { CascadeType.ALL })
   @JoinColumn(name = "ID_FLAVOR_FK", referencedColumnName = "id_flavor")
   private Flavor flavor;

   @ManyToOne(cascade = { CascadeType.ALL })
   @JoinColumn(name = "ID_SIZE_FK", referencedColumnName = "id_size")
   private Size size;
}
@Entity
@Table(name = "tb_flabor_position_filling")
class FlaborPositionFilling {

    @EmbeddedId
    private FlaborPositionFillingEmbeddedId id;
    private Integer position;
}

@Embeddable
class FlaborPositionFillingEmbeddedId implements Serializable {
    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name="ID_FLAVOR_FK", referencedColumnName="id_flavor")
    private Flavor sabor;

    @ManyToOne()
    @JoinColumn(name="ID_FILLING_FK", referencedColumnName="id_filling")
    private Filling filling;
}

我已经阅读了很多关于这两者的内容,但仍然不了解每种方法的正确用法及其对操作的影响。谁能给我解释一下?显示视频、图片、代码...

假设您有父 -> 子关系。

如果您在关系上设置 CacadeType.REMOVE,每次 EntityManager.remove 对父项的调用也会删除子项。

orphanRemoval = true用于删除孤儿。

因此,如果从父引用或集合中删除子项并保存父项,则子项将被删除,因为它不再依附于父项。