2017-05-30 85 views
1

我在,用户可以从列表中删除子实体的情况:删除子实体时重新连接父实体

@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);时,子实体仍然存在。

回答

3

您需要更进一步设置@OneToMany上的孤儿删除。使用标准CascadeType.DELETE,您需要明确删除该实体。随着孤儿的删除,你只需要从列表中清除它,就像你做的那样:

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

像魔术一样工作 –