0

You can imagine I have some service, say it will be money service. Also assume I have one method, that perform actual transfer (Quite mundane example, I know). And I have to return true if transaction ended up successfully, and false, if it is not. So, here is the think that I do not actually grasp - how do I track the result of transaction in Spring Framework? (May be even for just simple logging purposes) Example of my transfer method is present below. Appreciate any help.

@Transactional
    public boolean transferMoneyFromOneAccountToAnother(MoneyTransferForm moneyTransferForm) {
        final UserBankAccount sourceBankAccount = bankAccountRepository.findBankAccountByIdentifier(
                moneyTransferForm.getSourceAccountIdentifier()
        );
        final UserBankAccount targetBankAccount = bankAccountRepository.findBankAccountByIdentifier(
                moneyTransferForm.getTargetAccountIdentifier()
        );
        subtractMoneyFromSourceAccount(moneyTransferForm, sourceBankAccount);
        appendMoneyToTargetAccount(moneyTransferForm, targetBankAccount);
        bankAccountRepository.updateUserBankAccount(sourceBankAccount);
        bankAccountRepository.updateUserBankAccount(targetBankAccount);
    }
Mikhail
  • 195
  • 2
  • 12

1 Answers1

0

I can think of two ways to do it:

  1. You can simply enclose your method call with try/catch block and if there are no exception then your transaction was committed successfully.

    try{
         transferMoneyFromOneAccountToAnother()
    
         logger.info("Transacton Done Successfully");
    
     }catch(Exception ex){
          //transaction failed
          logger.error("Transaction failed")
     }
    
  2. You can have a method which is annotated with @TransactionalEventListener and listening to your custom event. You can check these links for more understanding of how it works: https://www.baeldung.com/spring-events
    @TransactionalEventListener annotated method not invoked in @Transactional test

Arun Singh
  • 16
  • 2