2011-10-16 25 views
1

我試圖加載我的服務類的init方法從DB一些數據,但是當我稱之爲「getResultList()」方法,那麼它拋出一個異常「會議閉幕」。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) 

所以我在做什麼錯在這裏?我該如何解決這個問題?謝謝。

回答

2

所有TestServiceImpl首先不與@Transactional註解,但即使它是,它不會工作,請參閱:Transactional init-methodSPR-2740 - 這也解釋這是由設計。

你可以做的是使用init()方法只調用其他bean的業務方法,標記爲@Transactional

private TestDao testDao; 

public void init() { 
    testDao.findAll(); 
} 

而且在TestDao豆:

private EntityManager entityManager; 

@Transactional 
public findAll() { 
    Query query = entityManager.createQuery("from myTable"); 
    return query.getResultList(); 
} 
+0

感謝您的回答,調用一些其他bean的業務方法奏效了,通過我已經有@Transactional服務類的方式(忘了把它放在這個問題),但是你如果是甚至有提到它不會奏效。 – Rizwan