0

在 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)并执行一些操作。然而,捕获代码永远不会到达。

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

任何帮助表示赞赏!

4

1 回答 1

0

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

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

于 2012-06-12T15:40:03.117 回答