在Spring中如何捕获Hibernate SQL异常

3

我在Spring中使用Hibernate执行SQL语句,但为了处理异常,我使用了Hibernate Exception和SQL Exception。但是,当我的SQL服务器离线或无法访问时,我无法捕获异常,而是遇到错误。

org.hibernate.exception.JDBCConnectionException 

这里的name.save(user);是执行SQL命令的Hibernate命令。

如何捕获此类异常。

我一直收到错误消息:

对于JDBCConnectionException,无法捕获异常块。此异常从try语句主体中永远不会被抛出。

对于SQLException,无法捕获异常块。此异常从try语句主体中永远不会被抛出。

我的代码:

try
{
      ApplicationContext appContext = 
              new ClassPathXmlApplicationContext("/config/BeansInfo.xml");
    TokenBo tokenBo = (TokenBo)appContext.getBean("TokenBo");
    TokenModel token = new TokenModel();
    token.setNumber(Number);
    token.setID(ID);
}

catch(JDBCConnectionException ex  )
{
  System.out.println(ex);
}
catch(SQLException e){}

我还想捕获SQL非可执行异常,比如主键冲突,如何捕获这些异常? - Labeo
可能是Hibernate异常处理的重复问题。 - Lukasz Szozda
@Labeo永远不要在注释中添加额外的信息;始终更新您的问题-不要期望其他人阅读(可能很长)的注释列表。 - GhostCat
3个回答

2

在连接相关的异常情况下使用JDBCConnectionException,在违反约束条件的情况下使用ConstraintViolationException。根据您的要求使用其他异常。请参见此处


捕获JDBCConnectionException的catch块无法到达。该异常从try语句体中永远不会被抛出。 - Labeo
使用多个catch块而不是使用OR。 - Esty
能否给我提供一些示例代码?因为我也在使用Spring MVC + Hibernate开发。这个对我非常有帮助。 - Esty
你能提供一些解决方案吗? - Labeo
1
实际上,由于您正在使用Spring MVC,我建议您使用AOP的GlobalExceptionHandler来处理异常。这样会更好。 - Esty
显示剩余2条评论

1
除了 @Tanjim Rahman 之外,
代码片段
在 UserDAOImpl.java 中,
使用 ConstraintViolationException 捕获重复的条目。
@Override
public String addUser(User user) 
{
    Session openSession = sessionFactory.openSession();
    String retStr = null;

    try
    {
        openSession.getTransaction().begin();
        openSession.persist(user);
        openSession.getTransaction().commit();

        retStr = "success";
    }
    catch (ConstraintViolationException e)
    {
        openSession.getTransaction().rollback();

        String[] tmpArr =  e.getSQLException().toString().split(":");
        String[] anotherTmpArr = null;

        if( tmpArr.length > 1)
        {
            anotherTmpArr = tmpArr[1].split("for key");
        }

        retStr = anotherTmpArr[0];

    }
    catch (HibernateException e) 
    {
        retStr = e.getLocalizedMessage();
    }

    finally 
    {
        openSession.close();
    }


    return retStr;
}

0

你只能捕获直接抛出给你的异常(至少对于已检查的异常...)。如果你真的想以任何合理的方式处理这个特定的错误情况,有可能捕获抛出给你的异常并检查异常的原因。

try {
    // some hibernate calls
} catch (GenericJdbcException ge) {
    if(ge.getCause() != null && ge.getCause() instanceof SQLException) {
        SQLException se = (SQLException)ge.getCause();
        if(se.getErrorCode() == -911) {
            // your error handling for this case
        }else{
            throw ge; // do not swallow unhandled exceptions
        }
    }else{
        throw ge // do not swallow unhandled exceptions
    }
}

感谢 Oracle社区


我无法使用GenericJdbcException,它要求我创建一个类。 - Labeo
尝试使用此链接:https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6/html/API_Documentation/files/javadoc/org/hibernate/exception/GenericJDBCException.html - wiretext

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接