我希望在完成@Transactional
的方法后将数据写入数据库。在使用HSQL数据库时,这是我的JUnit测试的有效假设。我正在使用HSQL db进行开发,而Oracle则用于我已部署的应用程序。部署在WebSphere上的Web App,在RSA中开发。
以下是我的配置摘要,包括POM和junit测试:
POM:
3.2.9.RELEASE
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.3</version>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.1</version>
APPLICATION CONTEXT:
<!-- the bean for transaction manager for scoping/controlling the transactions -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dbDataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<jee:jndi-lookup id="dbDataSource" jndi-name="jndi/HSQLDatasource" expected-type="javax.sql.DataSource" />
<!--Mapper-->
<bean id="campaignMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface"
value="com.abc.persistence.mapper.CampaignMapper" />
<property name="sqlSessionTemplate">
<bean class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactoryForBatch" />
<constructor-arg index="1" value="BATCH" />
</bean>
</property>
</bean>
<!-- SqlSessionFactory For Batch -->
<bean id="sqlSessionFactoryForBatch" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dbDataSource" />
<property name="typeAliasesPackage" value="com.abc" />
<property name="mapperLocations" value="classpath*:com/mybatis/mappers/**/*.xml" />
</bean>
JUNIT:
//junit class extends a base class that initializes HSQL db
//jdbcConnection.setAutoCommit(false);
@Autowired
CampaignMapper campaignMapper;
@Transactional
@Test
public void testInsert(){
for(Campaign record:campaignsFromFile){
record.setRowLastUpdateId(rowLastUpdateId);
record.setCampaignId(campaignId);
campaignMapper.insertCampaignRecord(record);
}
//At this point I expect that the data would NOT be written to the database
//other method code
}//end of method
//At this point I expect that the data would be written to the database
答案 0 :(得分:2)
默认情况下,Spring将在测试上下文中回滚事务。如果这不是您期望的行为,则始终可以使用@Rollback
注释false
值:
@Transactional
@Test
@Rollback(false)
public void testInsert() { ... }
如果您使用的是Spring 4.2.x版本,则可以使用新的@Commit
注释,这是一个新注释,可用作@Rollback(false)
的直接替代。您可以在 Spring Test Context here中阅读有关事务管理的更多信息。