在复杂的用户事务(ut)中,我们必须找到一个 JPA 实体,添加一个新的子实体,然后再次找到父实体。我们观察到,当我们在事务中获取父级时,子级列表不完整,并在事务提交后按预期完成。一切都是单线程的,并使用相同的实体管理器实例。
我们是否遗漏了一些可以解释这种行为的明显的东西?
ut.begin();
// find the parent entity
ParentEntity parent = em.find(parentKey);
assertEquals(parent.getChildren().size(), 1); // as expected
// add one child
ChildEntity child = createChild(); // create child for the parent
child.setParentRef(parent.getRef());
em.persist(child);
em.flush();
// find the parent entity again
ParentEntity parent = em.find(parentKey);
assertEquals(parent.getChildren().size(), 1); // UNEXPECTED! Should be two...
ut.commit();
// find the parent entity again
ParentEntity parent = em.find(parentKey);
assertEquals(parent.getChildren().size(), 2); // now I see 2 children. After committing
父级关系定义如下:
@OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinColumn(name="parent_ref", referencedColumnName="ref")
List<ChildEntity> children = new ArrayList<ChildEntity>();
最佳答案
这完全在意料之中。您设置了子项的父项,但未将子项添加到父项列表中。所有这些都在单个事务中,因此第二次调用 em.find(parentKey)
返回的父对象直接来自一级缓存,因此与返回的对象完全相同第一次通话。
您有责任维护事务中对象图的一致性。请参阅http://docs.jboss.org/hibernate/core/4.3/manual/en-US/html_single/#tutorial-associations-usingbidir
关于java - 解析交易中的一对多关系会返回不完整的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21450767/