Why are transactions not rolling back when using SpringJUnit4ClassRunner/MySQL/Spring/Hibernate

前端 未结 5 1240
谎友^
谎友^ 2021-02-06 16:04

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

相关标签:
5条回答
  • 2021-02-06 16:48

    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>
    
    0 讨论(0)
  • 2021-02-06 16:49

    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.

    0 讨论(0)
  • 2021-02-06 16:51

    This must be used

    @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
    @TestExecutionListeners({ TransactionalTestExecutionListener.class })
    @Transactional
    

    TransactionalTestExecutionListener contains isRollback() which rollbacks the transaction after the test method.

    0 讨论(0)
  • 2021-02-06 16:57

    For me defaultAutoCommit and @Transactional didn't help. I had to change db type to InnoDB

    0 讨论(0)
  • 2021-02-06 17:01

    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.

    0 讨论(0)
提交回复
热议问题