1

我有使用 Hibernate (3.6.9.Final) 的 Spring MVC (3.1.1.RELEASE) 应用程序。它配置了 Log4j。

log4j.category.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.event.def.AbstractFlushingEventListener=OFF

当我尝试在表中添加一行时,如果字段的长度超过最大大小,在日志中我可以看到这个异常:

hibernateTemplate.merge(ba);

在日志中:

2012-07-06 15:22:35,546 ERROR [org.hibernate.util.JDBCExceptionReporter] - <ERROR: value `too long for type character varying(70)>`

但另一方面,在我的代码中,我只能捕捉到这个DataAccessException异常:

Could not execute JDBC batch update; SQL [insert into T_MYTABLE (BA_NUMBER, USR_ID, BA_ID) values (?, ?, ?)]; nested exception is org.hibernate.exception.DataException: Could not execute JDBC batch update"}

这不是我想要的例外。

您知道如何在我的应用程序中从日志文件中获取消息吗?

我试过捕捉HibernateException但没有成功。

4

2 回答 2

0

我遇到了同样的问题。这是我在筛选了所有各种包装器和无用的通用错误后得到的结果。似乎应该有更好的方法。我觉得这很脆弱并且是特定于实现的。

@ExceptionHandler(DataAccessException.class)
@ResponseBody
public ErrorResponse handleDataAccessException(DataAccessException e, HttpServletResponse response) {
    String errorString = null;
    Throwable t = e.getCause();      
    if(t instanceof PersistenceException) {
        t = t.getCause();
        if(t instanceof ConstraintViolationException) {
            t = t.getCause();
            if(t instanceof BatchUpdateException) {             
                SQLException sqlException = null;
                sqlException =  ((SQLException) t).getNextException();
                if(sqlException instanceof PSQLException) {
                    errorString = ((PSQLException)sqlException).getServerErrorMessage().toString();
                    log.error("Caught exception: type=\"" + sqlException.getClass().getSimpleName() + " " + errorString);
                }
            }
        }
    }
    response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
    ErrorResponse errorResponse = new ErrorResponse();
    Set<ResultCode> resultCodes = new HashSet<ResultCode>();
    resultCodes.add(ResultCode.SERVER_ERROR);
    errorResponse.setResultCodes(resultCodes);
    return errorResponse;
}
于 2014-04-23T23:31:45.757 回答
0

我设法找到了一种方法:

 catch(DataAccessException e)
    {
            Throwable t = e.getCause();               
            SQLException ex = (SQLException) t.getCause();
            while(ex != null){
                 while(t != null) {
                     t = t.getCause();
                 }
                 logger.warn("SQLException="+ex.getLocalizedMessage());

                 ex = ex.getNextException();
            }
    } 

来源:https ://forum.hibernate.org/viewtopic.php?f=1&t=987395&view=previous

于 2012-07-06T09:54:40.297 回答