SQL Zone is brought to you in partnership with:

Gabriel Jeremiah Campbell has a Bachelor of Science Honours Degree in Applied Mathematics and Computer Science from the National University of Science and Technology (NUST). I am a Sun Certified Java Programmer(SCJP) and Sun Certified Web Component Developer(SCWCD). I have worked as Junior Lecturer in Computer Science for 3 years. I have been actively developing software in Java for 4 years. I have also coded in C/C++. When not at a computer (or thinking about a computer) I enjoy sci-fi movies, cycling, nature walks and photography. Gabriel Jeremiah is a DZone MVB and is not an employee of DZone and has posted 9 posts at DZone. You can read more from them at their website. View Full User Profile

Nice and Naughty Transactions in Hibernate and Spring

12.03.2010
| 9319 views |
  • submit to reddit

I came across a very interesting fact about Spring transaction management. Spring provides us with two ways of handling transaction

  1. Using proxies,
  2. Using DI through the getTemplate() method.

Now what happens when we consider 1) we mean:

Declaring in an XML file the transactionManager and transactionTemplate bean:

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" singleton="true">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" singleton="false">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
</bean>  

Then we use proxies and provide:

<bean id="myTableManagerTx" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" singleton="true" lazy-init="true">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target">
<ref bean="myTableManagerImpl"/>
</property>
<property name="transactionAttributes">
<props>
<prop key=" *">PROPAGATION_NOT_SUPPORTED,readOnly</prop>
</props>
</property>
<property name="preInterceptors">
<list>
<ref bean="callMonitor"/>
</list>
</property>
</bean>

 

With the use of interceptors we can now use doInHibernate() and have transaction support without any extra coding:

protected Object updateObject(final Context ctx, final Object o) {
return getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return update(ctx, session, o);
}
});
}

 

However we can use alternative 2)

try {

TransactionTemplate transactionTemplate = SpringFactory.getTransactionTemplate( TransactionDefinition.ISOLATION_READ_COMMITTED, TransactionDefinition.PROPAGATION_REQUIRED, false );

return ( List )transactionTemplate.execute( new TransactionCallback() {

public Object doInTransaction( TransactionStatus transactionStatus ) {
return getMyTableDAO().find( ctx, myId );

}
} );
} catch( Exception e ) {
log.error( e.getMessage(), e );
}

Here we are programmatically creating a transaction based on Spring’s DI.

What happens if we use both together? That is 1) and 2) in an application we could have errors like: 

Session cannot be closed!

This is because we are using proxies for transactions and also programmatically controlling transactions. If our TransactionDefinition fields :PROPAGATION_REQUIRED, PROPAGATION_NEVER, PROPAGATION_NOT_SUPPORTED,PROPAGATION_REQUIRES_NEW etc are not adjusted and used correctly we could have problems and errors with sessions being closed prematurely and incorrectly controlled. Also the HibernateTemplate controls the sessions for us. As stated in the Spring documentation:

The central method is execute, supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions. For typical single step actions, there are various convenience methods (find, load, saveOrUpdate, delete).

This can lead to sessions not being closed properly and resources not been freed and hence lead to memory leaks(Which I have experienced!). Final word of advice is: carefully watch your transactions!

From http://gabrieljeremiahcampbell.wordpress.com/2010/08/31/nice-and-naughty-transactions-in-hibernate-and-spring/

Published at DZone with permission of Gabriel Jeremiah Campbell, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Nicolas Frankel replied on Fri, 2010/12/03 - 3:28am

Hi,

You can also consider another option and use @Transactional in conjunction with <tx:annotation-driven />. It will let you choose which method you would want to make transactional and not make them so by default (which is what you did with the * pattern). As of now, it is my prefered method for managing trasactions (at the cost of coupling my code to Spring).

Attila Király replied on Fri, 2010/12/03 - 3:34am in response to: Nicolas Frankel

@Transactional +1 (together with OpenEntityManagerInViewFilter)
The original example seems to be 1.4 compatible however. That could be a deciding factor for some environments.

Hantsy Bai replied on Mon, 2010/12/06 - 3:31am in response to: Attila Király

@Transactional with OpenEntityManagerInViewFilter(the declarative way) is only  for web application, if the appliation is a service application, such as an Rest web service producer for the client application(either webapplication or desktop application) and  u want to control the transaction demarcation yourself, the programatic approach is a good choice.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.