I am doing unit testing and I expect that all data committed to the MySQL database will be rolled back... but this isn\'t the case. The data is being committed, even though my
The problem turned out to be that the connection was auto-committing BEFORE the transaction could be rolled back. I had to change my dataSource bean to include a defaultAutoCommit property:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="Ecosim07"/>
<property name="defaultAutoCommit" value="false" />
</bean>
Another way to fix your problem:
Instead of using:
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
, which creates a MyISAM table by default, hence not supporting transactions
Try using
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
, which creates InnoDB tables, and thus supports transactions.
This must be used
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@TestExecutionListeners({ TransactionalTestExecutionListener.class })
@Transactional
TransactionalTestExecutionListener contains isRollback() which rollbacks the transaction after the test method.
For me defaultAutoCommit and @Transactional didn't help. I had to change db type to InnoDB
I hope I am right and that this is a simple one. You are missing the @Transactional annotation on your test class. This means that the test method itself isn't run in a transaction and thus there is nothing to roll back. Hope this helps.