gpt4 book ai didi

java - Spring MVC 4 服务@tTransactional 不起作用

转载 作者:行者123 更新时间:2023-11-30 06:55:30 25 4
gpt4 key购买 nike

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)) 这种情况失败 Expected : 1 but Actual : 0

第二次 TC 失败意味着发生异常但不回滚删除评论

deleteCommentAndFiles 方法 抛出异常但不回滚

我正在尝试使用 @Transactional(propagation=Propagation.REQUIRED, rollbackFor={IncorrectUpdateSemanticsDataAccessException.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com