编辑5:
用于探索这个问题的解决方案的代码在 bitbucket 上:https ://bitbucket.org/jcalleja/lazy-init-exception
我意识到 SO 上还有许多其他 LazyInitializationException 帖子,但我无法从他们那里获得我需要的信息。
涉及的项目:
- memdrill 数据
- 数据使用
memdrill-data 是一个 Spring Roo 托管项目。这里没有 Web 组件。我有简单的:
persistence setup --provider HIBERNATE --database HYPERSONIC_PERSISTENT
并添加了一些实体。例如:
@RooJavaBean
@RooToString
@RooEntity
public class Item {
@NotNull
@Column(unique = true)
@Size(min = 1, max = 200)
private String itemId;
@NotNull
@Lob
@OneToOne(cascade = javax.persistence.CascadeType.ALL, fetch = FetchType.LAZY)
private LobString content;
}
@RooJavaBean
@RooEntity
public class LobString {
@Lob
@Basic(fetch=FetchType.LAZY)
private String data;
public LobString() {
super();
}
public LobString(String data) {
this.data = data;
}
}
没关系,但为了记录,我使用的是 Roo 1.1.4。可能在此讨论中不需要 applicationContext.xml,但无论如何都需要它(由 Roo 生成后未触及):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
<context:spring-configured/>
<context:component-scan base-package="com.memdrill.data">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
数据使用取决于 memdrill-data,我现在只是通过它测试驱动 memdrill-data。这就是数据使用中发生的所有事情:
public static void main(String[] args) {
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
"classpath*:META-INF/spring/applicationContext*.xml");
Item item = new Item();
item.setItemId("abc123");
item.setContent(new LobString("this is the content of the item"));
item.persist();
System.out.println("persist - OK");
List<Item> items = Item.findAllItems();
Item i = items.get(0);
System.out.println("i.getId() = " + i.getId());
System.out.println("i.getItemId() = " + i.getItemId());
System.out.println("i.getContent() = " + i.getContent());
System.out.println("i.getContent().getId() = " + i.getContent().getId());
System.out.println("i.getContent().getData() = " + i.getContent().getData());
appContext.close();
}
findAllItems() 是 Roo 在 Item_Roo_Entity.aj 中生成的默认值:
public static List<Item> Item.findAllItems() {
return entityManager().createQuery("SELECT o FROM Item o", Item.class).getResultList();
}
这就是我得到的:
persist - OK
i.getId() = 1
i.getItemId() = abc123
2014-07-05 13:23:30,732 [main] ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.memdrill.data.util.LobString_$$_javassist_0.toString(LobString_$$_javassist_0.java)
at java.lang.String.valueOf(String.java:2826)
at java.lang.StringBuilder.append(StringBuilder.java:115)
at com.memdrill.prototypes.datause.Main.main(Main.java:34)
因此,当我尝试访问延迟加载的数据以填充 LobString POJO 时,没有正在进行的会话并且它崩溃了。
我能得到的最接近的(在我的代码中,即不是我所依赖的库)放入 LobString 访问代码(例如,item.getContent().getId())就像推入 findAllItems() 或创建像这样的新方法只是为了说明这一点:
public static List<Item> findAllItemsWithRefs() {
List<Item> items = entityManager().createQuery("SELECT o FROM Item o", Item.class).getResultList();
for(Item item : items) {
System.out.println("item.getContent().getId() = " + item.getContent().getId());
}
return items;
}
这仍然给了我同样的例外,这意味着在 .getResultList() 返回列表之后没有会话正在进行。
正如其他 SO 帖子所建议的那样,我已经尝试将 @Transactional 放在该方法上,但我仍然得到 LazyInitializationException。但即使这确实有效......为什么我需要启动一个事务来从数据库中读取数据?事务不是为了在写入时保持数据完整性吗?
在我看来,解决这个问题的一种方法是以某种方式从“SELECT o FROM Item o”中指定一个不同的查询……一个也获取 LobString 数据的查询……但这似乎不太正确,即使它会在这种特殊情况下飞行。
当我访问尚未加载的数据时,我期待 Hibernate 启动一个新会话......但显然,它不像我预期的那样工作。
熟悉 Hibernate 的人可以解释在这种情况下发生了什么,并可能建议可以使用哪些选项来处理这个问题?
谢谢
编辑1:
顺便说一句,如果我将以下 log4j.propeties 添加到类路径:
log4j.rootLogger=error, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
我得到:
persist - OK
2014-07-05 16:17:35,707 [main] DEBUG org.hibernate.SQL - select item0_.id as id1_, item0_.content as content1_, item0_.item_id as item2_1_, item0_.version as version1_ from item item0_
2014-07-05 16:17:35,711 [main] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - found [1] as column [id1_]
2014-07-05 16:17:35,713 [main] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - found [1] as column [content1_]
2014-07-05 16:17:35,713 [main] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - found [abc123] as column [item2_1_]
2014-07-05 16:17:35,713 [main] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - found [0] as column [version1_]
i.getId() = 1
i.getItemId() = abc123
2014-07-05 16:17:35,717 [main] ERROR org.hibernate.LazyInitializationException - could not initialize proxy - no Session
因此,正如“found 1 as column [content1_]”行所示,我至少拥有包含 LobString 数据的表中行的外键......但如果没有 LazyInitializationException,我无法访问该 ID。也许我可以如果我能拿到 LobString,请按 id 获取...但是 i.getContent() 和 i.getContent().getId() 给出异常。外键应与 LobString 表的主键 id 匹配 ieigetContent( ).getId().. 但似乎无法从 i... 访问外键,正如日志所示,它实际上是从数据库中获取的。
无论如何,即使我确实得到了外键......不得不留下 LobString.find(id) 或类似的东西不是一个好的解决方案。Hibernate 应该填充您的对象图...
编辑2:
在此编辑中要提出 2 点。执行通过以下方式org.springframework.orm.jpa.SharedEntityManagerCreator.DeferredQueryInvocationHandler.invoke(Object, Method, Object[])
:
// Invoke method on actual Query object.
try {
Object retVal = method.invoke(this.target, args);
return (retVal == this.target ? proxy : retVal);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
finally {
if (method.getName().equals("getResultList") || method.getName().equals("getSingleResult") ||
method.getName().equals("executeUpdate")) {
EntityManagerFactoryUtils.closeEntityManager(this.em);
}
}
首先,如果使用“getResultList”,EntityManager 将被关闭。我假设 EntityManager 是一个 JPA 构造,无需详细说明,它映射到 Hibernate 的 Session。
第二......如果我在调试时深入研究,我可以看到应该延迟加载的数据“这是项目的内容”......所以我实际上已经将该数据加载到内存中...... 1)因为它是懒惰的不应该 2) 即使它在那里我也无法访问它,因为我得到了 LazyInitializationException。
在调试时,我可以看到数据加载在以下两个地方:
1)我的主要方法(见上文:主要方法中的Item i = items.get(0))
com.memdrill.prototypes.datause.Main.main(String[])
:
i -> 内容 -> 处理程序 -> 目标 -> 数据:“这是项目的内容”
2)在关闭会话的方法中
org.springframework.orm.jpa.SharedEntityManagerCreator.DeferredQueryInvocationHandler.invoke(Object, Method, Object[])
::
retVal -> elementData[0] -> content -> handler -> target -> data: "this is the content of the item"
懒惰加载的数据太多了……我做错了什么?
我似乎也有延迟加载 LobString 的规范。但如果是这样的话,而且我确实有内存中的内容......为什么我不能访问它?
编辑3:
如果我在调试模式下保持足够长的时间,它看起来只有在调试时才会发生 Edit2 中的行为(在内存中延迟加载数据).....
所以基本上,如果我在调试中运行并且只是通过我的断点一直点击“播放”“播放”“播放”,我会得到 LazyInitializationException ......但是如果我在调试模式下停留足够长的时间,没有 LazyInitializationException,我会得到数据并打印到标准输出。
有任何想法吗?
编辑4:
感谢SO question,我现在可以使用以下方法急切地获取所有 LobString:
EntityManager em = Item.entityManager();
List<Item> items = em.createQuery("SELECT o FROM Item o JOIN FETCH o.content", Item.class).getResultList();
输出:
2014-07-06 21:44:56,862 [main] INFO org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'persistenceUnit'
in LobString default constructor
in LobString (String data) constructor
2014-07-06 21:44:57,891 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Creating new transaction with name [com.memdrill.data.entity.Item.persist]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2014-07-06 21:44:57,944 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl@779d9c0d] for JPA transaction
2014-07-06 21:44:57,948 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Not exposing JPA transaction [org.hibernate.ejb.EntityManagerImpl@779d9c0d] as JDBC transaction because JpaDialect [org.springframework.orm.jpa.DefaultJpaDialect@d7e60a1] does not support JDBC Connection retrieval
2014-07-06 21:44:57,999 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Initiating transaction commit
2014-07-06 21:44:58,000 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Committing JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl@779d9c0d]
2014-07-06 21:44:58,002 [main] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl@779d9c0d] after transaction
2014-07-06 21:44:58,002 [main] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
persist - OK - in Main of memdrill-data not data-use
2014-07-06 21:44:58,008 [main] DEBUG org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler - Creating new EntityManager for shared EntityManager invocation
in LobString default constructor
2014-07-06 21:44:58,133 [main] DEBUG org.springframework.orm.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
i.getId() = 1
i.getItemId() = abc123
i.getContent() = com.memdrill.data.util.LobString@6fe30af
i.getContent().getId() = 1
i.getContent().getData() = this is the content of the item
2014-07-06 21:44:58,134 [main] INFO org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'persistenceUnit'
这几乎就是我想要的。我只想要 LobString 的 id。这个想法是这将是一个 REST 调用,我只想返回可用于单独请求的 LobString 的 Item “基本”数据和 id。
知道什么样的 JPQL 查询可以实现这一点吗?(任何有助于理解幕后情况的一般评论将不胜感激) - 谢谢