删除子实体时重新连接父实体
问题描述:
我在,用户可以从列表中删除子实体的情况:删除子实体时重新连接父实体
@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<>();
像魔术一样工作 –