【发布时间】:2018-07-05 02:20:40
【问题描述】:
我是 Spring 新手,正在使用 Spring jdbc 编写示例程序。这是为了检查 spring @Trsactional 如何工作并在出现异常时回滚对 Db 的更改。
但我无法做到这一点。通过我在其中一个数据库更新中引发异常,它仍然将数据插入数据库而不是回滚该批次。例如。插入 5000 后,我引发了一个异常,因此理想情况下,它应该将所有更改(针对当前批次)回滚到所有表,并且 Db 中的总行数应为 4000。
我知道我在某个地方犯了错误,但无法弄清楚。不确定这是否是正确的方法。
我尝试了互联网上所有可能的方法,但仍然没有运气。请帮我解决这个问题。
这是我的示例应用程序https://github.com/rajarshp/JavaSample
代码片段
@Transactional(rollbackFor={Exception.class})
public void executeDB(int count) throws Exception
{
CreateAccount newacc = new CreateAccount(jdbcTemplate);
CreateUser newusr = new CreateUser(jdbcTemplate);
//BalanceUpdate newbal = new BalanceUpdate(jdbcTemplate);
newacc.addList(acclist);
newusr.addToList(usrlist);
//newbal.addList(ballist);
newusr.execute(); // insert data to db
newacc.addAccount(); // insert data to db
//newbal.addBalance(); // insert data to db
newacc.getAccList().clear();
newusr.getUserList().clear();
//newbal.getBalanceList().clear();
if(count == 5000)
{
Thread.sleep(1000);
throw new Exception("Rollback");
}
count += 1000;
//throw new Exception();
}
XML:
<context:component-scan base-package="com.example"></context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="startit" class="com.example.springtransaction.GlobalClass">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="dbupdate" class="com.example.springtransaction.DbUpdate">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
【问题讨论】:
-
你的
@Transactional没用。您正在执行内部方法调用。 Spring AOP 使用代理,因此只有进入对象的方法调用将通过代理,而不是内部方法调用。 -
@M. Deinum 你介意告诉我我需要为此更改代码的哪一部分吗?因为我有点困惑
标签: java spring jdbc transactions spring-transactions