init-method中的getResultList()给出错误“会话已关闭”

时间:2011-10-16 20:39:08

标签: java spring jpa applicationcontext

我试图在我的服务类的init方法中从DB加载一些数据,但是当我调用“getResultList()”方法时,它会抛出异常“会话关闭”。

我的applicationContext.xml

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />    
<bean id="testService" class="com.impl.TestServiceImpl" init-method="init" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

我的服务类:

public Class TestServiceImpl implements TestService {
private EntityManager entityManager;

@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
   this.entityManager = entityManager;
}   

public void init() {
    Query query = entityManager.createQuery("from myTable");
    query.getResultList();  // this causes error...
}
}

这是错误消息:

SEVERE: Exception sending context initialized event to listener instance of class 
org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
'testService' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: 
Invocation of init method failed; nested exception is
javax.persistence.PersistenceException: org.hibernate.SessionException: Session is 
closed!
Caused by: javax.persistence.PersistenceException: org.hibernate.SessionException: 
Session is closed!
at 
org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:630)

那我在这里做错了什么?我该如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:2)

首先,您的TestServiceImpl未使用@Transactional进行注释,但即使有init(),也无效,请参阅:Transactional init-methodSPR-2740 - 这解释了这是设计的。

您可以做的是仅使用@Transactional方法调用其他bean的业务方法,该方法标记为private TestDao testDao; public void init() { testDao.findAll(); }

TestDao

private EntityManager entityManager; @Transactional public findAll() { Query query = entityManager.createQuery("from myTable"); return query.getResultList(); } bean中:

{{1}}