Hibernate Transaction Annotation Configuration

David Winterfeldt

2008


Creating basic transaction using annotations with Spring for Hibernate.

1. Spring Configuration

To process annotation-based transaction configuration a transactionManager bean needs to be created and this will be used by <tx:annotation-driven/> for managing transactions.

PersonDaoTransactionTest-context.xml
                
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">

    <import resource="classpath:org/springbyexample/orm/hibernate3/shared-context.xml"/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven/>
   
    <bean id="personDao" class="org.springbyexample.orm.hibernate3.dao.PersonDaoImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
 
</beans>