开发者

Can't clear a list of related entity beans from an entity bean

开发者 https://www.devze.com 2023-04-12 14:46 出处:网络
I\'m trying to run the code below, but I keep getting the error \"Cannot merge an entity that has been removed\".

I'm trying to run the code below, but I keep getting the error "Cannot merge an entity that has been removed".

My DB tables look like this:

banner
-id

banner_period
-id
-banner_id
-date

My Java code:

Banner b = getEntityManager().find(banner.getId());
List<BannerPeriod> bps = b.getBannerPeriodList();
for (BannerPeriod bp : bps) {
    getEntityManager().remove(bp);
}
// <-- removed code that adds periods here
b.setBannerPeriodList(bps);
getEntityManager().merge(b);

I can't seem 开发者_开发百科to understand the logic in all this. Could anyone explain what it is, I'm missing here? I've tried to search for answers already, but I find it hard to define keywords that give me relevant results.

UPDATE:

Banner entity:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "bannerId")
private List<BannerPeriod> bannerPeriodList;

BannerPeriod entity:

@JoinColumn(name = "banner_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Banner bannerId;


List<BannerPeriod> bps still contains references to BannerPeriods. So when you call merge on b here is what happens.

merge on b
-> Cascade all on  bannerPeriodList
-> Iterate over bannerPeriodList and merge them
**ERROR** The values in bannerPeriodList have been removed.

Try this

bps.clear();
b.setBannerPeriodList(bps);
getEntityManager().merge(b);
0

精彩评论

暂无评论...
验证码 换一张
取 消