简体   繁体   English

事务不回滚 JPA 保存在 spring 启动

[英]Transactional not rolling back JPA save in spring boot

I am working on a spring boot app where I am using transactional and its not rolling back its changes when I throw a exception:我正在开发一个 spring 启动应用程序,在该应用程序中我正在使用事务性并且当我抛出异常时它不会回滚其更改:

My method:我的方法:

private BtoBWalletTransactionResponseModel doWalletOperation(BtoBWalletTransactionTypes transactionType, BtoBWalletTransactionRequestModel transactionRequest) {
            // DB Operation
            BtoBWalletTransaction savedTransaction = commonTransactionalService.finishWalletTransaction(userWallet, btoBWalletTransaction);
            log.info("wallet {} txn of amount {} for user {}",transactionType.name(),txnAmount,userId);
            // throwing a exception to rollback
            throw new RuntimeException("Time to Rollback");
            
        } catch(Exception e){
            log.error(e.getMessage());
            log.error("error while doing wallet operations for user {}",userId);
            throw new WalletException(e.getMessage());
        }

    }

My common TransactionalService Interface:我常用的 TransactionalService 接口:

public interface CommonTransactionalService {

    BtoBWalletTransaction finishWalletTransaction(BtoBUserWallet userWallet,BtoBWalletTransaction btoBWalletTransaction);

}

My Interface Impl:我的接口实现:

import javax.transaction.Transactional;

@Service
public class CommonTransactionalServiceImpl implements CommonTransactionalService {

    @Autowired
    private BtoBWalletTransactionRepo btoBWalletTransactionRepo;

    @Transactional
    @Override
    public BtoBWalletTransaction finishWalletTransaction(BtoBUserWallet userWallet, BtoBWalletTransaction walletTransaction) {
        BtoBWalletTransaction savedTransaction = btoBWalletTransactionRepo.save(walletTransaction);
        btoBUserWalletRepo.save(userWallet);
        return savedTransaction;
    }

}

Now even when I am sending a RuntimeException the DB record is not getting rolled back.现在,即使我发送RuntimeException数据库记录也不会回滚。 Can someone help?有人可以帮忙吗? stuck since hours here.在这里停留了几个小时。

Transactional is scoped, if you anotate a method (or class) as @Transactional all the methods this class calls wil also be transactional.事务是作用域的,如果您将方法(或类)注释为@Transactional ,则此 class 调用的所有方法也将是事务性的。 and if within this transaction an exception occurs things wil be rolled back.如果在此事务中发生异常,则将回滚。

If however like in you example a non-transactional method calls a transactional one and after that call throws an exception the previous transactioned function wil not be rolled back as it's outside of the transactions scope.但是,如果像在您的示例中那样,非事务性方法调用事务性方法,并且在该调用引发异常之后,先前的事务 function 将不会回滚,因为它在事务 scope 之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM