Home > Uncategorized > User defined exception thrown in Spring Transaction

User defined exception thrown in Spring Transaction

This post is a result of a problem I faced while working on one of my project. Spring is used for managing transactions and we have not upgraded to Spring 2.5 annotation based transaction. But the concept here is important not the code

We had service class which had transaction attributes defined in applicationContext.xml file as

<bean id=”helloService” parent=”txProxyTemplate”>

<property name=”target”>
<bean
class=”com.skillguru.impl.HelloServiceImpl”
autowire=”byName” />
</property>

<property name=”transactionAttributes”>
<props>
<prop key=”*”>PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>

Within the same file,  the transaction proxy template is defined as

<bean id=”txProxyTemplate” abstract=”true”
class=”org.springframework.transaction.interceptor.TransactionProxyFactoryBean”>
<property name=”transactionManager”>
<ref bean=”transactionManager” />
</property>
<property name=”transactionAttributes”>
<props>
<prop key=”save*”>PROPAGATION_REQUIRED</prop>
<prop key=”remove*”>PROPAGATION_REQUIRED</prop>
<prop key=”*”>PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>

The class HelloServiceImpl throws a User defined exception, UserDuplicateException

The logic is that a method HelloServiceImpl#saveUser inserts the user ina  aloop and then checks for duplicate user based on some coniftions.

If the user is duplicate , none of the records are to inserted.

This works fine on paper but not in real world. Reason being UserDuplicateException is  a user defined exception and not a an instance or subclass of RuntimeException, Spring was not rolling back the transaction.

Look at Spring docs here

For the transaction to roll back, the exception has to be configured like this

<bean id=”helloService” parent=”txProxyTemplate”>

<property name=”target”>
<bean

autowire=”byName” />
</property>

<property name=”transactionAttributes”>
<props>
<prop key=”*”>PROPAGATION_REQUIRED,-UserDuplicateException</prop>
</props>
</property>
</bean>

Look at -UserDuplicateException. This is the key here. For a user defined exception to rollback , you to have define it explicitly with a -ve sign.

Things have changed in newer version of Spring but the concept is still same.

Other Spring related posts

Spring Interview Questions

Which is better : Spring’s Transaction management or EJB’s Container managed transaction


Categories: Uncategorized Tags:
  1. No comments yet.
  1. No trackbacks yet.