重新附加父实体时删除子实体

remove child entity when re-attach the parent entity

我有一种情况,用户可以从列表中删除子实体:

@Entity
public class StandaredPriceTag {
.
.
.
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER,mappedBy="standaredPriceTag")
List<StandaredPrice> standaredPriceList = new ArrayList<>();

@Entity
public class StandaredPrice {
    .
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "standard_price_tag_id")
    private StandaredPriceTag standaredPriceTag;
    .

据我了解,只要 StandaredPriceTag 附加到实体管理器,任何更新都将反映到数据库中。现在,当我从 List<StandaredPrice> standaredPriceList 中删除一个项目然后将 StandaredPriceTag 重新附加为 entityManager.merge(standaredPriceTag); 时,子实体仍然存在。

您需要进一步设置 @OneToMany 上的孤立删除。使用标准 CascadeType.DELETE,您需要显式删除该实体。删除孤立项后,您只需像之前一样将其从列表中清除:

@OneToMany(cascade = { CascadeType.ALL }
  , fetch = FetchType.EAGER,mappedBy="standaredPriceTag"
  , orphanRemoval = true)
List<StandaredPrice> standaredPriceList = new ArrayList<>();