gpt4 book ai didi

java - orphanRemoval 在 hibernate 状态下无法正常工作 : Element inserted and removed from list is persisted in DB

转载 作者:行者123 更新时间:2023-11-30 08:56:56 24 4
gpt4 key购买 nike

我们有一个问题,听起来像是 Hibernate 处理 orphanRemoval=true 对于 oneToMany List 的错误>(带索引)。

这是简化的映射:

public class ParentClass {

[...]

@OneToMany(cascade = ALL, mappedBy = "parent", orphanRemoval = true)
@OnDelete(action = OnDeleteAction.CASCADE)
@Fetch(FetchMode.JOIN)
@OrderColumn(name = "pos", nullable = false)
public List<ChildClass> getChildren() {
return children;
}

}

还有子类:

public class ChildClass {
[...]

@ManyToOne
@JoinColumn(nullable = false, name = "parent_id")
public ParentClass getParent() {
return parent;
}
}

给定此映射,以下情况将失败:

  1. 从数据库中获取一个Parent
  2. 给它添加一个 child
  3. 从数据库(不是同一个实体)获取其他东西,产生部分刷新
  4. 从父项中移除子项
  5. 离开交易

这是代码

@Transactional
public void test() {

// 1)
ParentClass parent = entityManager.find(ParentClass.class, "some-id");

// 2)
ChildClass child = new ChildClass(parent);
parent.getChildren().add(child);

// 3)
entityManager.find(SomethingElse.class, "2");

// 4)
parent.getChildren().remove(child);
}

在这种情况下,子分配将插入到数据库中,并且不会在事务结束时删除。

但是,如果我们不执行第 3 步),则子分配不会正确地保存在数据库中

这是一个错误吗?错误的映射?有解决方法吗?

最佳答案

是的,这是一个错误。我敢打赌您不会使用最新版本的 Hibernate (4.3.8),并且它与此问题相关(如果不是同一问题):[HHH-9330] orphanRemoval=true does not work in bidirectional relationships (without cascading)即使您使用最新版本,此错误仍可能存在。如果是这样,请报告它,然后在此处报告错误的 URL。解决方法:仅在确定必须保留子项时才尝试添加子项,或者也尝试将子项中的父项设置为 null:

child.setParent(null);

另外,作为另一种解决方法,您可以尝试使用 Hibernate session ,而不是 EntityManager(因为它写在 Hibernate 的论坛中)。

关于java - orphanRemoval 在 hibernate 状态下无法正常工作 : Element inserted and removed from list is persisted in DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28370940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com