无法从实体 bean 中清除相关实体 bean 的列表
我正在尝试运行下面的代码,但我不断收到错误“无法合并已删除的实体”。
我的数据库表看起来像这样:
banner
-id
banner_period
-id
-banner_id
-date
我的 Java 代码:
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);
我似乎无法理解这一切的逻辑。谁能解释一下这是什么,我在这里失踪了?我已经尝试过搜索答案,但我发现很难定义能够为我提供相关结果的关键字。
更新:
横幅实体:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "bannerId")
private List<BannerPeriod> bannerPeriodList;
BannerPeriod 实体:
@JoinColumn(name = "banner_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Banner bannerId;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
列表bps
仍然包含对BannerPeriod
的引用。因此,当您在b
上调用 merge 时,会发生以下情况。试试这个
List<BannerPeriod> bps
still contains references toBannerPeriod
s. So when you call merge onb
here is what happens.Try this