【问题标题】:Spring Hibernate Exception HandlingSpring Hibernate 异常处理
【发布时间】:2012-06-12 14:38:51
【问题描述】:

在 Spring + Hibernate + JTA 项目中,我试图让异常处理工作。对于以下代码:

@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public HandsetManufacturer createHandsetManufacturer(
        HandsetManufacturer handsetManufacturer)
        throws HandsetManufacturerAlreadyExistsException{
    HandsetManufacturer handsetManufacturer2=new  HandsetManufacturer();
    try {

            handsetManufacturerDao.findByUniqueProperty(
                HandsetManufacturer.class, NAME_PROPERTY,
                handsetManufacturer.getName());
        throw new HandsetManufacturerAlreadyExistsException();
    } catch (BusinessObjectNotFoundException ignoreMe) {
    }
    //handsetManufacturer2= handsetManufacturerDao.create(handsetManufacturer);

    try{
        handsetManufacturer2= handsetManufacturerDao.create(handsetManufacturer);
    }catch (JDBCException e) {
        System.out.println("::HibernateException::"+e.getSQL());
        System.out.println("::HibernateException::"+e.getErrorCode());
        System.out.println("::HibernateException::"+e.getSQLState());
        System.out.println("::HibernateException::"+e.getSQLException());
        System.out.println("::HibernateException::"+e.getMessage());
        System.out.println("::HibernateException::"+e.getCause());
        throw new TechnicalException(e);
    }

    return handsetManufacturer2;
}

我正在尝试捕获底层 hibernate/jdbc/db 异常(例如,当依赖实体仍然存在时,删除将失败并出现 org.springframework.orm.hibernate3.HibernateJdbcException)并执行一些操作。但是永远不会到达 catch 代码。

但如果我从我的方法中删除“@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)”,它将到达 catch 块。 我想这与 Spring 管理它的方式有关,但我不知道如何在 JDBCException 期间捕获异常并使用 @Transaction 注释

感谢任何帮助!

【问题讨论】:

    标签: spring hibernate jta


    【解决方案1】:

    我猜你的 DAO 也被配置为具有 REQUIRED 传播的事务。在 Hibernate 中,有很多动作会延迟到会话刷新。刷新发生的时间之一是在事务提交之前。这意味着如果您的方法(我猜它是某些服务中的方法)正在围绕它进行事务处理,那么在您的 DAO create() 中的 Hibernate 持久化或保存操作实际上不会进入数据库,直到您的服务方法完成。

    一种解决方法是显式执行 Session flush()(您可以考虑放入 DAO 的 create()),以便触发数据库更新,从而导致您期望抛出的异常。

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多