I'm trying to do funds tranfer from Source Account to destination Account using JDBC declarative transaction and JDBC Template.
Use Case: If I try to call fundsTransfer method when source account does't have enough balance. In that case amount is getting added in destination account even though withdraw() throwing expected 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);
}
Note: If we call withdraw() before deposit() in fundsTranser, getting the expected exception.
Used Data Base - SQLServer
Could someone help me out here, what I'm missing here? Ideally, the reflected amount in destination account should get rollback because withdraw ends with an exception.