【问题标题】:How to rollback a transaction in subclass when an exception is thrown in super class超类中抛出异常时如何回滚子类中的事务
【发布时间】:2018-07-08 08:30:43
【问题描述】:

考虑 Spring MVC 4 中的以下场景:有一个继承 GenericDao 的子类 RoleDaoRoleDao 中的方法 createRole() 使用程序化事务管理调用 GenericDao 中的两个方法 method1,method2method1method2 都可以自行捕获异常。请参阅下面的代码。我的问题是如何在超类GenericDaomethod1method2 中抛出异常时在方法createRole 中回滚事务

public class RoleDao extends GenericDao {

public int createRole() {
try
    {
       TransactionDefinition def = new DefaultTransactionDefinition();
      TransactionStatus status = transactionManager.getTransaction(def);
    this.methhod1();
    this.methhod2();
    transactionManager.commit(status);

    }
    catch (InvalidResultSetAccessException e) 
    {
    transactionManager.rollback(status);
        throw new RuntimeException(e);
    } 
    catch (DataAccessException e)
    {
    transactionManager.rollback(status);
        throw new RuntimeException(e);
}
}
public class GenericDao{

public int method1() {
try
    {
       ..........
    .........
    }
    catch (InvalidResultSetAccessException e) 
    {
        throw new RuntimeException(e);
    } 
    catch (DataAccessException e)
    {
        throw new RuntimeException(e);
    }
}
public int method2() {
try
    {
       .........
    .........
    }
    catch (InvalidResultSetAccessException e) 
    {
        throw new RuntimeException(e);
    } 
    catch (DataAccessException e)
    {
        throw new RuntimeException(e);
    }
}
}

【问题讨论】:

  • 当您说回滚时,您可能是指前滚?

标签: spring model-view-controller exception-handling transactions


【解决方案1】:

删除超类方法中的所有异常,它们应该由子类方法处理。

【讨论】:

    【解决方案2】:

    尝试使用弹簧注解。 @Transactional over RoleDao 类可能会帮助你。

    【讨论】:

    • 我无法将声明式和程序化事务管理结合起来。关于程序化,我引用“提供了极大的灵活性,但很难维护”
    猜你喜欢
    • 2020-09-24
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2019-01-21
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多