抛出异常时如何在休眠状态下执行事务

时间:2018-10-03 04:54:44

标签: java spring hibernate

在事务服务层中,我使用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);
}

如您所见,在else if (userAccount.isExpired())块中,我要先删除userAccount,然后引发异常。但是由于它引发异常并突然退出该方法,因此不会执行删除。

我想知道是否有任何方法可以在引发异常时继续执行删除操作。

1 个答案:

答案 0 :(得分:3)

我也遇到过同样的情况。

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

使用该课程,您可以在失败事件发生后采取行动。

在这里看, https://www.baeldung.com/spring-security-custom-authentication-failure-handler