2012-06-12 44 views
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; 
} 

我试图抓住潜在的休眠/ JDBC/DB异常(例如,当实体依赖仍然存在删除将失败,org.springframework.orm.hibernate3.HibernateJdbcException)并执行一些操作。但是,捕获代码永远不会到达。

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

任何帮助表示赞赏!

回答

0

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

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