Search
Calendar
May 2025
S M T W T F S
« Apr    
 123
45678910
11121314151617
18192021222324
25262728293031
Archives

PostHeaderIcon Transaction Management with Spring in AOP

Case

You have a couple of Hibernate DAOs, in which a huge amount of code is duplicated: begin transactions, try/catch, close transactions, etc.
You would like to factorize your code.

Fix

  • Define a SessionFactory, let’s say hibernateSessionFactory, with your own settings.
    <bean id="hibernateSessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">(...)</bean>
  • Define a TransactionManager:
    <bean id="hibernateTransactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
    <ref local="hibernateSessionFactory" />
    </property>
    </bean>
  • Define transactions advices:
    <tx:advice id="hibTxManager" transaction-manager="hibernateTransactionManager">
    <tx:attributes>
    <tx:method name="*" propagation="NEVER" read-only="true" isolation="READ_COMMITTED" rollback-for="find*" no-rollback-for="dontFind*"/>
    </tx:attributes>
    </tx:advice>
    • name="*" –> the aspect will apply to all methods. You may filter on patterns such as find*, get*, save*, etc.
    • propagation="NEVER" –> hints the propagation level. Available options are
    • REQUIRED, SUPPORTS, MANDATORY,REQUIRES_NEW, NOT_SUPPORTED, NEVER, NESTED.
    • isolation="READ_COMMITTED" –>
    • rollback-for="find*" –> rollback all transactions following the given pattern
    • no-rollback-for="dontFind*" –> exceptions for rollbacks
  • Define the AOP configuration:
    <aop:config>
    <aop:pointcut id="hibOperation"
    expression="execution(* com.lalou.jonathan.dao.hibernate.Hibernate*.*(..))" />
    <aop:advisor pointcut-ref="hibOperation" advice-ref="hibTxManager" />
    </aop:config>

Many thanks to Jean-Pierre ISOARD for his help on this subject.

Leave a Reply