Spring JUnit JPA Transaction Not Rollback

I am trying to test my DAO, which uses the JPA EntityManager to retrieve and update objects. I marked my unit test as Transactional and set the defaultRollback property to false. However, I do not see my transactions returning at the end of the test when throwing a time exception in RuNet. Data is stored in the database. Here is my unit test code and spring configuration. I obviously missed something, but could not determine what. Btw, transaction - RESOURCE_LOCAL in persistence.xml file

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring/test-jpa.xml"}) @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class }) @TransactionConfiguration(defaultRollback=false) @Transactional public class JpaTests { @PersistenceContext EntityManage em; @Test public void testTransactionQueueManager() { Object entity = em.find(1); //code to update entity omitted. entity = em.merge(entity); em.flush(); throw new RuntimeException } } 

Spring Configuration

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jpa.driverclassname}" /> <property name="url" value="${jpa.url}" /> <property name="username" value="${jpa.username}" /> <property name="password" value="${jpa.password}" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="${jpa.persistenceunitname}"/> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"> <property name="databasePlatform" value="org.apache.openjpa.jdbc.sql.DBDictionary"/> </bean> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 
+4
source share
3 answers

Your configuration seems beautiful. There may be different reasons for unexpected commit, possibly an auto-mode data source or a transaction-compatible database (mysql with MyISAM?)

You checked this topic. Why transactions do not roll back when using SpringJUnit4ClassRunner / MySQL / Spring / Hibernate ?

+1
source

@TransactionConfiguration (defaultRollback = false)

may be the culprit. Try defaultRollback = true, which should cancel the transaction.

0
source

Adding rollbackFor may help, this is a common mistake.

 @Transactional(rollbackFor=Exception.class) 
0
source

Source: https://habr.com/ru/post/1480623/


All Articles