gpt4 book ai didi

java - 为什么 EntityManager.merge() 会阻止 LazyInitializationException 而 EntityManager.find() 不会?

转载 作者:行者123 更新时间:2023-11-29 09:23:51 27 4
gpt4 key购买 nike

给定网络应用程序中的以下情况:

// EntityManager em, one per Request with Spring's OpenEntityManagerInViewFilter
// Parent oldParent, from previous request (and therefore another persistence context)
Parent parent = em.find(Parent.class, oldParent.getId());
List<Child> children = parent.getChildren(); // Mapped collection with LazyLoading
for (Child child : children) {
...

列表迭代器的调用导致 LazyInitializationException。这很令人困惑,因为子列表的获取发生在相同的持久性上下文中(或者我错了吗?)。但是,使用merge(),它可以工作。就好像两个请求共享一个持久化上下文。

Parent parent = em.merge(oldParent);
List<Child> children = parent.getChildren();
for (Child child : children) {
...
// No Exception!!

我的推理错误是什么?

添加
我已经证明错误不是由 parent.getId() 引起的。这是堆栈跟踪的一部分:

at org.hibernate.collection.PersistentList.iterator(PersistentList.java:138)

这意味着实际上是迭代器导致了问题。它变得更加奇怪 - 我已经检查过在第一种情况下(使用 find()),hibernate 发出了一个 select 语句来从数据库中检索一个新对象,而不是从缓存中持久性上下文。

加法2
这里有更多的堆栈跟踪信息:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: edeka.sw.phb.model.Chapter.subChapters, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:365)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:108)
at org.hibernate.collection.PersistentList.iterator(PersistentList.java:138)
at java.util.Collections$UnmodifiableCollection$1.<init>(Collections.java:1022)
at java.util.Collections$UnmodifiableCollection.iterator(Collections.java:1021)
//... followed by the line of the foreach.

最佳答案

我认为您的问题不在迭代部分,因为您使用最近加载的新父项进行迭代。问题必须出在似乎未加载的 .getId() 上,然后合并才起作用,因为不调用 .getId()

关于java - 为什么 EntityManager.merge() 会阻止 LazyInitializationException 而 EntityManager.find() 不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4326039/

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