【问题标题】:remove child entity when re-attach the parent entity重新附加父实体时删除子实体
【发布时间】:2017-10-31 02:56:46
【问题描述】:

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

@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&lt;StandaredPrice&gt; standaredPriceList 中删除一个项目,然后将StandaredPriceTag 重新附加为entityManager.merge(standaredPriceTag); 时,子实体仍然存在。

【问题讨论】:

    标签: java hibernate jpa orm persistence


    【解决方案1】:

    您需要更进一步,在 @OneToMany 上设置孤儿删除。使用标准CascadeType.DELETE,您需要显式删除实体。通过孤立删除,您只需像以前一样从列表中清除它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      相关资源
      最近更新 更多