jpa延迟加载在生产模式下失败 - 在测试模式下它工作正常

时间:2012-06-07 11:24:47

标签: spring hibernate jpa

我调用服务来加载实体。如果我在集成测试中运行它很好,但在服务器上的现实生活中它会失败。

此实体中的某些属性是集合。在这两种情况下,实体都加载了bean。当我在debugmode中使用“query.getSingleResult()”附近的断点停止执行时,我看到,集合已加载。但只是在一个测试中......

我在servletcontainer中停止相同的代码并获得InvocationException!?

我的环境看起来像:
弹簧3.1
hibernate 3.6.6.Final

我尝试过的事情:
- 在context.xml中搜索差异(测试和生产)
- 在productionmode中使用其他context.xml文件(test)

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: de.hoeso.gwt.platform.server.domain.common.Person.anschrift, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122) at org.hibernate.collection.PersistentBag.size(PersistentBag.java:248) at de.hoeso.sis.server.services.common.impl.UserServiceBeanImpl.login(UserServiceBeanImpl.java:397) at de.hoeso.sis.server.rpc.LoginService.execute(LoginService.java:35)

我发现,在testmode中,hibernate会话已连接并打开。在productionmode中(在servletcontainer中,entitymanager.getDelegate()没有连接的hibernatesession。

1 个答案:

答案 0 :(得分:0)

现在我在JMelnik的帮助下找到了我自己问题的解决方案。为后人,我将分享我的解决方案......

在我将一个断点放在我加载对象的代码附近后,我看到了主要的区别。

return entitymanager.isOpen();

(布尔值)true // testmode和productionmode

return ((org.hibernate.Session)entitymanager.getDelegate()).isConnected();

(boolean)true //在testmode中 (boolean)false //在productionmode中

return ((org.hibernate.Session)entitymanager.getDelegate()).isOpen();

(boolean)true //在testmode中 (boolean)false //在productionmode中

return((org.hibernate.Session)entitymanager.getDelegate()).getTransaction().isActive();  

在productionmode中抛出异常 在testmode中,它返回:(boolean)true

结论:代码在没有事务的生产模式下运行。在测试模式下,存在一个事务,因为测试类继承自一个超类,该超类用@Transactional注释。在ServiceBean的层次结构中,我忘记了这一点。

插入注释,一切都完美无缺!