Java 如何在引发异常时在hibernate中执行事务

Java 如何在引发异常时在hibernate中执行事务,java,spring,hibernate,Java,Spring,Hibernate,在使用Hibernate实现的事务服务层中,我有以下方法: @Override public void activateAccount(String username, String activationCode) throws UsernameNotFoundException, AccountAlreadyActiveException, IncorrectActivationCodeException { UserAccountEntity user

在使用Hibernate实现的事务服务层中,我有以下方法:

@Override
public void activateAccount(String username, String activationCode)
        throws UsernameNotFoundException, AccountAlreadyActiveException,
        IncorrectActivationCodeException {
    UserAccountEntity userAccount = userAccountRepository.findByUsername(username);
    if (userAccount == null) {
        throw new UsernameNotFoundException(String.format("User %s was not found", username));
    } else if (userAccount.isExpired()) {
        userAccountRepository.delete(userAccount);
        throw new UsernameNotFoundException(String.format("User %s was not found", username)); 
    } else if (userAccount.isActive()) {
        throw new AccountAlreadyActiveException(String.format(
                "User %s is already active", username));
    }
    if (!userAccount.getActivationCode().equals(activationCode)) {
        throw new IncorrectActivationCodeException();
    }
    userAccount.activate();
    userAccountRepository.save(userAccount);
}
如您所见,在
elseif(userAccount.isExpired())
块中,我想首先删除
userAccount
,然后抛出一个异常。但是当它抛出异常并突然退出该方法时,不会执行delete


我想知道是否有任何方法可以在抛出异常时保持删除操作。

我也遇到过同样的情况

我的解决方案是使用Spring Security FailureHandler

使用此类,您可以在发生故障事件后执行操作

看这里,

我想知道一般情况下应该做什么,而不仅仅是在安全相关代码中。但是我认为我不能使用它,因为将它放在过滤器中不是一个跨领域的问题,它是业务逻辑的一部分。您应该检查日志,查看提取的UserAccountEntity是否存在。(如果为null)从这段代码中,我认为它混淆了执行哪个块。因为它们抛出相同的异常。它绝对不是空的。我可以在调试程序和数据库中看到它。当我注释掉抛出新用户名NotFoundException(…)时,它会删除该行。我想这就是发生的事情。在事务服务层中,在方法正常完成时提交事务,如果抛出异常(甚至我们自己的异常),事务将回滚(即未提交)。我想知道如何避免这种情况,并告诉Hibernate它很好,应该提交事务。显然,它会回滚,因为这是一个运行时异常: