Spring JUnit How to Rollback Database Transaction

It’s common when you are testing your DAOs at a safe TDD environment to perform the DB action, assertThat what you’ve done is as expected and then safely rollback the transaction. All should look untouched at the DB level (except the DB sequences that are always moving forward) thereafter.

The annotations needed in the JUnit test class to achieve this are:

@ContextConfiguration(locations = "/pathTo/spring/context/applicationContext.xml")
@TransactionConfiguration(transactionManager = "jdbcTransactionManager", defaultRollback = true)
public class LocationDaoTest {
  @Inject daoInTest;
  public void testDAOsCRUD(){}


  • The ContextConfiguration annotation points to the main application’s context configuration file.
  • The TransactionConfiguration annotation points to your transaction manager defined in your application context which can either be a DataSourceTransactionManager for JDBC operations or a HibernateTransactionManager for Hibernate related ORM operations.
  • The defaultRollback=true attribute of the TransactionConfiguration is responsible for rolling back safely our test transactions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s