【发布时间】: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