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 toBannerPeriod
s. So when you call merge onb
here is what happens.Try this