1. Spring MVC application-context.xml
<tx:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="test"/>
<property name="password" value="test"/>
<property name="url" value="jdbc:mysql://localhost:13306/test"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
2. Service impl class
@Override
@Transactional
public void deleteCommentAndFiles(int commentId) {
int deletedCommentCount = commentDAO.deleteComment(commentId);
int deletedFileCount = fileDAO.deleteFiles(commentId);
if (deletedCommentCount != 1) {
throw new IncorrectUpdateSemanticsDataAccessException("Deleted comment not 1 [deletedCount : " + deletedCommentCount);
}
if (deletedFileCount != 1) {
throw new IncorrectUpdateSemanticsDataAccessException("Deleted file not 1 [deletedCount : " + deletedCommentCount);
}
}
3. Test Case
@Test
public void rollbackT() {
boolean hasException = false;
int sizeBeforDelete = commentDAO.selectCountByArticle(1);
try {
commentService.deleteCommentAndFiles(1);
} catch (RuntimeException e) {
hasException = true;
}
Assert.assertTrue(hasException);
Assert.assertEquals(sizeBeforDelete, commentDAO.selectCountByArticle(1));
}
在测试用例中
首先Assert.assertTrue(hasException);
通过,但
Assert.assertEquals(sizeBeforDelete, commentDAO.selectCountByArticle(1))
这种情况下失败 Expected : 1 but Actual : 0
这第二个TC失败意味着发生异常,但不回滚删除注释
deleteCommentAndFiles method
抛出异常但不回滚
我正在尝试使用 @Transactional(propagation=Propagation.REQUIRED, rollbackFor={IncorrectUpdateSemanticsDataAccessException.class})
但同样行不通
为什么@Transactional注释不起作用?
我也遇到过同样的问题。我将@transactional移到了控制器上才能正常工作。
@EnableTransactionManagement并仅在定义它们的相同应用程序上下文中在bean上查找@Transactional。这意味着,如果将注释驱动的配置放在DispatcherServlet的WebApplicationContext中,则仅检查控制器中的@Transactional bean。您的服务。有关更多信息,请参见第21.2节“ DispatcherServlet”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句