Cannot get @Rollback to work for my Spring JPA Int

2019-04-29 01:21发布

问题:

This here is a little test class that I have. Problem is that it is not rolling back the transaction after each test run. What have I done wrong? :)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/META-INF/catalog-spring.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class TermTest
{
    @Autowired
    private CatalogService service;
    @Rollback(true)
    @Test
    public void testSimplePersist()
    {   
        Term term = new Term();
        term.setDescription("Description");
        term.setName("BirdSubject8");
        term.setIsEnabled("F");
        term.setIsSystem("F");
        term.setTermType("TERM");
        service.createTerm(term);
    }
}

and my spring config

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="catalog2"></property>
</bean>

<bean id="catalogService" class="com.moo.catalog.service.CatalogService">
    <property name="termDao" ref="termDao"></property>
</bean>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />

回答1:

You need @Transactional in addition to @TransactionConfiguration:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "/META-INF/catalog-spring.xml" }) 
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) 
@Transactional
public class TermTest { ... }


回答2:

in spring 4.0 later because TransactionConfiguration is deprecated

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/config/spring-config.xml")
@Transactional
public class UserTest {
    @Rollback
    public void test(){
    }
}