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。服务实现类
@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
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))
这种情况失败 预期:1 但实际:0
第二个TC失败意味着发生异常但不回滚删除评论
deleteCommentAndFiles方法
抛出异常但不回滚
我正在尝试使用@Transactional(propagation=Propagation.REQUIRED, rollbackFor={In CorrectUpdateSemanticsDataAccessException.class})
但同样不起作用
为什么@Transactional注释不起作用?
最佳答案
我也遇到了同样的问题。我将 @transactional 移至 Controller 以便正常工作。
@EnableTransactionManagement and only looks for @Transactional on beans in the same application context they are defined in. This means that, if you put annotation driven configuration in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. See Section 21.2, “The DispatcherServlet” for more information.
关于java - Spring MVC 4 服务@tTransactional 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308657/