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

1.5k views Asked by At

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;
1

There are 1 answers

3
Mark Robinson On BEST ANSWER

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);