【问题标题】:Transaction is not getting rollback when use JDBC Declarative Transactions使用 JDBC 声明式事务时事务没有回滚
【发布时间】:2020-09-10 23:38:45
【问题描述】:

我正在尝试使用 JDBC 声明性交易和 JDBC 模板将资金从 来源 帐户转移到 目的地 帐户。

用例:如果我在源账户余额不足时尝试调用 fundsTransfer 方法。在这种情况下,即使withdraw() 抛出预期的 InSufficientFundsExceptions,也会在目标账户中添加金额。

@Autowired
JdbcTemplate jdbcTemp;
-----
-----
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public void deposit(int accountNumber, double amount) {
    String sql = "select Balance from <TableName> where Account_Number=?";
    double balance = jdbcTemp.queryForObject(sql, Double.class, accountNumber);
    balance = balance + amount;
    String sql2 = "update <TableName> set Balance=? where Account_Number=?";
    jdbcTemp.update(sql2, balance, accountNumber);
}

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public void withdraw(int accountNumber, double amount) throws InSufficientFundsExceptions {

    String sql = "select Balance from <TableName> where Account_Number=?";
    double balance = jdbcTemp.queryForObject(sql, Double.class, accountNumber);
    if (balance >= 5000) {
        balance = balance - amount;
        String sql2 = "update <TableName> set Balance=? where Account_Number=?";
        jdbcTemp.update(sql2, balance, accountNumber);
    } else {
        throw new InSufficientFundsExceptions("InSufficientFunds Exception");
    }
}

@Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
public void fundsTransfer(int sourceAccountNumber, int destinationAccountNumber, double amount)
        throws InSufficientFundsExceptions {

    deposit(destinationAccountNumber, amount);
    withdraw(sourceAccountNumber, amount);
}

注意:如果我们在fundsTranser 中的deposit() 之前调用withdraw(),会得到预期的异常。

使用的数据库 - SQLServer

有人可以帮助我吗,我在这里缺少什么?理想情况下,目标账户中反映的金额应该得到回滚,因为提款以异常结束。

【问题讨论】:

  • 看来InSufficientFundsExceptions 不是RuntimeException 的子类。如果是这种情况,请使用 rollbackFor 定义方法 fundsTransfer() 的回滚行为
  • 您可能需要检查this answer 来解决类似问题

标签: java spring jdbctemplate spring-transactions


【解决方案1】:

原因是因为 Spring 默认只回滚未经检查的异常。因为你的类是一个检查异常,因为它不扩展 runtimeException 而是常规异常,所以它不做回滚。

您可以使用 @Transactional 注释中的 rollBackFor 属性并指定 insuffientFundsException 来修改此行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2015-03-12
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多