Transaction aware datasource (use dbunit & hibernate in spring)

April 27, 2008 at 5:03 pm | Posted in Uncategorized | 4 Comments
Tags: , ,


use dbunit & hibernate in unit test

  • prepare test data with dbunit using datasource
  • test a dao method with hibernate
  • rollback all data (each testcase doesn’t pollute data)


preparing test data and running a test method must be executed under the same transaction in order to rollback.
=> dbunit(datasource) needs to participate spring transaction management.


use TransactionAwareDatasourceProxy

[How it works]

Transaction manager acquires a DB connection and put it to connection holder in thread local.
Whenever getConnection() is called, same connection will be retrieved from connection holder.
When close() is called, it doesn’t close connection.
At the end of transaction, finally connection will be closed.

When transaction manager begins transaction, ConnectionHolder instance will be created and hold actual connection.
When transaction is done, connection will be closed.

wrap original datasource.
implementing DataSource interface
participate spring managed transaction control

proxy of Connection class
private inner class
delegate standard Connection methods(equals, close, …) to DataSourceUtils

[Sample Config]

 | Datasource with Transaction support.

<bean id="dataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
     <constructor-arg ref="dbcpDataSource"/>

<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
     <property name="driverClassName" value="${hibernate.connection.driver_class}"/>
     <property name="url" value="${hibernate.connection.url}"/>
     <property name="username" value="${hibernate.connection.username}"/>
     <property name="password" value="${hibernate.connection.password}"/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
    <property name="hibernateProperties" ref="hibernateProperties"/>
    <!--<property name="useTransactionAwareDataSource" value="true"/>-->

[Sample Test Code]

final IDatabaseConnection dbUnitConnection = new DatabaseConnection(this.getDataSource());

// Do some operations with dbunit
// eg)
// DatabaseOperation.DELETE.execute(connection, dataSet);

// this doesn't close connection since method is executed under transaction
DataSourceUtils.releaseConnection(dbUnitConnection.getConnection(), this.getDataSource());

[Key Spring Classes]


Create a free website or blog at
Entries and comments feeds.