It appears that the order in which the destory method is called for non-singleton bean objects is not completely controlled. From the documents ( 5.1.4 Using Dependence on ):
The dependency attribute in the component definition can indicate both the dependence of the initialization time, and, in the case of only single-element components , the corresponding dependence of the destruction time
You can create a helper object and instruct it to create and destroy your bean components:
public class HelperObject { private SessionFactory factory; private Session session; private Transaction tx; public void init() { session = factory.createSession(); tx = session.beginTransaction(); } public void destroy() { tx.commit(); session.close(); } ... }
-
<bean id = "helperObject" class = "HelperObject" scope = "request" init-method = "init" destroy-method = "destroy"> <property name = "factory" ref = "hibernateSessionFactory" /> </bean> <bean id="hibernateSession" factory-bean="helperObject" factory-method="getSession" scope="request" /> <bean id="hibernateTransaction" factory-bean="helperObject" factory-method="getTransaction" scope="request" />
And in the end, this may not be the best way to manage Spring Hibernate sessions and transactions. Consider using Spring Hibernate's built-in and transaction support.
EDIT: Well, the right way to manage transactions is:
- You do not need binary
session and transaction - You should not call
createSession for the session factory returned by org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean . You can embed this session factory in your beans and call getCurrentSession when you need a session, it will work fine. - You can use declarative transaction management (
@Transactional annotations for transactional methods). For this to work, you must add to your config:
,
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="hibernateSessionFactory"/> </bean> <tx:annotation-driven/>
- See the links above for more information.
axtavt
source share