如何正确捕获,包装和重新抛出Hibernate异常?

时间:2011-10-05 04:28:18

标签: java hibernate exception

我的数据库工作程序在Hibernate之上实现。如果出现问题,它的方法应该回滚事务并抛出SQLException。所以我的问题是:处理Hibernate异常的最佳(即最干净)方法是什么?目前我的所有方法看起来都像这样丑陋:

public EntryUserHib addUser(final String username, final String pwdhash) throws SQLException{
    try {
        final Transaction ta = sess.beginTransaction();
        try {
            // Using Hibernate here
            // "return" statement
        } catch(final HibernateException ex) {
            try {
                ta.rollback();
            } catch(final Exception ex1) {}
            throw ex;
        } finally {
            if (!ta.wasRolledBack()) ta.commit();
        }
    } catch(final HibernateException ex) {
        if (ex.getCause() != null) {
            if (ex.getCause() instanceof SQLException) throw (SQLException)ex.getCause();
            throw new SQLException(ex.getCause());
        }
        throw new SQLException(ex);
    }
}

2 个答案:

答案 0 :(得分:4)

根本不要抓住它们。 Hibernate异常扩展RuntimeException有两个很好的理由:您不必在方法签名中声明它们,并且任何RuntimeException都会自动导致事务回滚。异常处理会使代码变得非常混乱。 Hibernate人员的理念是HibernateExceptions应该是致命错误,信令编码或逻辑错误,并且在正常功能的应用程序中不应该(并且不需要)捕获。

您的应用程序的UI应该以用户友好的方式响应这些惊喜。这是一个单独的问题。

答案 1 :(得分:2)

让别人为你管理,就像Spring一样。它有extensive Hibernate and transaction support,它将提取您担心的所有代码。