我在 hibernate 时遇到了奇怪的问题。我的数据库关系如下所示:
Parent
@OneToMany(mappedBy = "parent", orphanRemoval = true)
@Cascade({CascadeType.ALL})
List<Child1> children1
Child1
@ManyToOne
@JoinColumn(name = "PARENT_ID")
Parent parent;
@OneToMany(mappedBy = "child1", orphanRemoval = true)
@Cascade({CascadeType.ALL})
List<Child2> children2;
Child2
@ManyToOne
@JoinColumn(name = "CHILD1_ID")
Child1 child1;
children1
和 children2
列表的大小始终为 1。
我们有这样的场景:清除 Parent.children1 列表(从数据库中删除行)并向该列表添加新的子项(向数据库插入新行)。不要问为什么我们要删除并插入新行而不是更新现有行,让我们假设这是必要的。这个场景看起来像:
- Clear
Parent.children1
list- Create new
Child2
- Create new
Child1
and add object created in point 2 (Child2
) tochildren2
list- Add object created in point 4 (
Child1
) tochildren1
list- Save
Parent
.
这是在一次事务中完成的。当在此事务期间我尝试在数据库中查找父项时(使用 hibernate ,在不同的事务中),我发现有时 children2
列表为空。怎么了?在将parent保存到数据库之前,我们总是向children2
列表添加一个Child2
对象,因此不应该出现children2
列表为空的情况。
最佳答案
请您执行以下步骤:
Parent parent = entityManager.find(Parent.class, id);
entityManager.lock(parent, LockModeType.WRITE);
parent.children1.clear();
看到结果了吗?
关于java - Hibernate孤儿移除-事务隔离级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37945118/