【问题标题】:Is there a way to translate HibernateException to something else, then DataAccessException in Spring有没有办法将 HibernateException 翻译成别的东西,然后是 Spring 中的 DataAccessException
【发布时间】:2014-01-01 02:31:10
【问题描述】:

我正在尝试更清楚地了解在 Hibernate 中的事务持久性期间发生的约束违反错误。

我了解如何干扰 HibernateExceptions 的唯一方法是在春季通过 PersistenceExceptionTranslator,

package org.springframework.dao.support;

import org.springframework.dao.DataAccessException;

public interface PersistenceExceptionTranslator {

    DataAccessException translateExceptionIfPossible(RuntimeException ex);

}

它将 Hibernate 异常转换为 DataAccessExceptions,但这意味着我需要从 DataAccessExceptions 继承我的异常层次结构。

有没有其他自然的方法可以做到这一点,而不在异常继承层次结构中引入 DataAceessExceptions?

【问题讨论】:

    标签: java spring exception jpa spring-data-jpa


    【解决方案1】:

    您可以捕获HibernateException 并将其作为已检查异常 从您的存储库方法中重新抛出。但是你将不得不处理上层的异常,但你也可以简单地把它扔到你的代码层之外。

    【讨论】:

    • 不太优雅,PersistenceExceptionTranslator 更好:)
    • 我知道,但是您要求不同的解决方案,所以我给您带来了一个 :) 除此之外,您不必扩展 DataAccessException
    • 也许您想使用@ExceptionHandler?见docs.spring.io/spring/docs/3.1.x/spring-framework-reference/…
    • 为什么不优雅?您可以在您的 dao 方法中捕获 HibernateException 并重新抛出。对我来说听起来很合理
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    相关资源
    最近更新 更多