如何在hibernate中获取MySQLIntegrityConstraintViolationException消息

如何在hibernate中获取MySQLIntegrityConstraintViolationException消息,hibernate,spring-mvc,Hibernate,Spring Mvc,我正在尝试处理异常 这是stacktrace org.hibernate.exception.ConstraintViolationException: could not execute statement at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59) at org.hibernate.exception.interna

我正在尝试处理异常

这是stacktrace

org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) 
    ...
    ...
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'testemail@gmail.com' for key 'UK_n7ihswpy07ci568w34q0oi8he'
当我尝试使用getMessage方法获取消息时,消息get是ConstraintViolationException中的无法执行语句

但我想得到的是 重复输入'testemail@gmail.com来自MySQLIntegrityConstraintViolationException的关键“UK_n7ihswpy07ci568w34q0oi8he”消息

这是我的捕捉过程

catch(MySQLIntegrityConstraintViolationException e){
    e.printStackTrace();
    message = "MySQLIntegrity,\n Duplicate Entry, \n" + e.getMessage();
}
catch(ConstraintViolationException e){
    e.printStackTrace();
    message = "ConstraintViolation,\n Duplicate Entry, \n" + e.getMessage();
}
catch (Exception e) {
    e.printStackTrace();
    message = "Exception rule,\n" + e.getMessage();
}
试一试

原因:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目'testemail@gmail.com'对于关键'UK_n7ihswpy07ci568w34q0oi8he'

这是最初的例外

简单变体:

private String getRootCauseMessage(Throwable ex){
    if(ex.getCause() == null){
        return ex.getMessage();
    }
    return getRootCauseMessage(ex.getCause());
}

但由于它是简单的变量,它们可能会无限递归。您可以添加一些计数器并计算递归调用。如果大于100,则返回空字符串

如果您有权访问apache commons,请使用它。
,有一个getRootCause方法可以提供根异常,您可以从一个获取masseage/

是,它提供了我所需要的。非常感谢。接下来的问题:如果我使用getCause方法,那么我可以得到异常的原因,但是如果有很多异常,getCause会给我所有的异常吗?非常感谢,先生。你救了我。谢谢你,先生。谢谢你的回答,这对我帮助很大。
private String getRootCauseMessage(Throwable ex){
    if(ex.getCause() == null){
        return ex.getMessage();
    }
    return getRootCauseMessage(ex.getCause());
}
Throwable cause = originalException;
while(cause.getCause() != null) {
    cause = cause.getCause();
}