【发布时间】:2018-06-15 13:18:01
【问题描述】:
我是 Spring 新手,正在使用 Spring jdbc 编写示例程序。这是为了检查 spring @Trsactional 如何工作并在出现异常时回滚对 Db 的更改。
但我无法做到这一点。通过我在其中一个数据库更新中引发异常,它仍然将数据插入数据库而不是回滚。
我知道我在某个地方犯了错误,但无法弄清楚。不确定这是否是正确的方法。
我在做什么:-
在主要方法中,我正在调用 Global 类的加载方法(它具有 jdbcTemplate 作为 satic 成员,因为我会将这个 jdbcTemplate 用于所有其他类)
全局类加载方法将使用 ApplicationContext 启动 bean。
在 main 方法中创建 Dbclass 实例并将 jdbcTemplate 作为参数发送。
4.创建一些样本数据并调用executeDb方法。
5.execute DB 方法将创建其他 Dbclass 的实例并设置我之前在 main 方法中使用 bean 初始化的 jdbcTemplate(我为每个操作都有单独的类 - 例如 createuser、UpdataBalance 等)
- 然后它会调用db操作方法插入数据(我使用的是batchupdate)
编辑 - 删除所有 try-catch
数据库操作码:-
@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();
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-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(rollbackFor = {Exception.class}) -
@Raizuri 是的,但这没有帮助。
-
您的代码正在吸收异常。删除 try-catch 块。
-
如果你使用@Transactional (rollbackFor = Throwable.class) 而不是@Transactional(rollbackFor = {Exception.class}) 会怎样
-
@user7005835 - 没有区别。
标签: java spring spring-mvc jdbc transactions