当前位置: 首页 > 知识库问答 >
问题:

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

云联
2023-03-14

我在使用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);
}

可以看到,在< code > else if(user account . is expired())块中,我想先删除< code>userAccount,然后抛出一个异常。但是由于它抛出了一个异常,并突然退出该方法,所以没有执行delete。

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

共有1个答案

栾鸣
2023-03-14

我也经历过同样的情况。

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

使用这个类,您可以在失败事件后采取措施。

看这里,https://www . bael dung . com/spring-security-custom-authentic ation-failure-handler

 类似资料:
  • 我使用的是Spring3.0.5和Hibernate3.6。在我的项目中,有一个场景,我必须回滚在抛出的任何异常或错误发生的事务。这是示例代码,除了当我抛出异常时事务不会回滚之外,一切都很好,但是如果抛出任何异常,比如mysql.IntegrityConstraintException,那么事务会回滚,为什么在我的情况下没有发生这种情况? hibernate.cfg 因此,正如我所说,我的问题是,

  • 问题内容: 我正在尝试引发异常(不使用try catch块),并且程序在引发异常后立即完成。有没有一种方法可以在我引发异常之后继续执行程序?我抛出了在另一个类中定义的InvalidEmployeeTypeException,但是我希望程序在抛出该异常后继续执行。 问题答案: 试试这个:

  • 我在A处有个方法 服务B中的另一种方法 我的问题是,例如,当“repository.insertRandomValue()”抛出ConstraintViolationException时,即使它在catch()中被捕获,线程也以 我尝试将传播设置为REQUIRES\u NEW,并尝试将transaction manager和GlobalRollbackOnParticipationFailure设

  • 我正在尝试使用Hibernate保存数据。一切都发生在同一会话中。逻辑如下: 1)开始交易并尝试保存: 2) 如果新记录违反完整性约束,请在外包装方法中捕获异常,打开另一个事务并查询更多数据 问题是当第二个事务执行时query.list它会抛出一个应该与前一个事务链接的异常。 SQLIntegrityConstraintViolationException:ORA-00001:唯一约束 我应该从另

  • 在用户任务上应用边界计时器事件,在服务任务上添加java类属性,但当计时器到期触发异常列表时,会抛出,即无法找到分配给服务任务的类。类存在于类路径上。activiti配置中还启用了asyncExecutorActivate属性 这里有一个代码 例外 Bean初始化

  • 在我的项目中,我将Hibernate与Spring和JPA结合使用。代码在服务层使用注释驱动的事务(使用@Transactional注释支持事务)。事务管理器是org.springframework.orm.hibernate4.HibernateTransactionManager。当任何@Transactional注释方法中发生异常时,当前事务将自动回滚。 我想知道如果我想在事务回滚时记录异常