AbstractTransactionalJUnit4SpringContextTests Failing to Rollback in MySQL?

Ok so today I was working on some JUnit tests within Spring using AbstractTransactionalJUnit4SpringContextTests (yes, wow what a long class name). For those of you unfamiliar with this class, basically if you extend your unit test class from this class, every @Test annotated test method will run within a transaction, with the default behavior being that a rollback is called after each @Test method’s execution (unless you declare so otherwise). Pretty convenient.

My simple test case was leveraging a DAO that derived from HibernateDaoSupport and the test inserted a few records. When the test was complete, another method annotated with @AfterTransaction would verify that the data did NOT exist in the table, which was expected due to the rollback that occurs after each test case…… well my asserts were failing because Hibernate created the MySQL tables using MyISAM, which does not support transactions. If you encounter this kind of issue, all you have to do is change your Hibernate dialect to use the MySQL5InnoDBDialect (for InnoDB storage which does transactions) within your session factory configuration as such:

<property name="hibernateProperties">
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

2 thoughts on “AbstractTransactionalJUnit4SpringContextTests Failing to Rollback in MySQL?

  1. Hi

    I’m having the same problem and unfortunately your solution didn’t work for me. I’m using:

    mysql –version
    mysql Ver 14.14 Distrib 5.1.37, for debian-linux-gnu (x86_64) using EditLine wrapper

    on Ubuntu. Is there something else I need to do?

    I’m not using Hibernate to create the actual tables. That’s done with a script from ant. could that be my problem?


  2. I found the answer. My tables needed to be of type INNODB:

    username varchar(50) NOT NULL UNIQUE,
    password varchar(50) ,
    enabled bit NOT NULL,

    ) TYPE = INNODB;

    CREATE TABLE Authorities
    username varchar(50) NOT NULL,
    authority varchar(50) NOT NULL,

    CONSTRAINT Pk_Authorities PRIMARY KEY CLUSTERED (username,authority ASC),
    CONSTRAINT Fk_Authorities_User FOREIGN KEY (username) REFERENCES Users (username)

    ) TYPE = INNODB;

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