java 如何在 SPRING 中捕获 Hibernate SQL 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32347083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:04:00  来源:igfitidea点击:

How to catch Hibernate SQL EXCEPTIONS IN SPRING

javasql-serverspringhibernate

提问by Labeo

i am using hibernate to execute sql statements in spring but to handle exceptions i used hibernate exception and sql exception but i am not able to handle exceptions

我正在使用 hibernate 在 spring 中执行 sql 语句但为了处理异常我使用了 hibernate 异常和 sql 异常但我无法处理异常

if my sql server is not on or not accessable i am not able to catch exception i am getting error

如果我的 sql server 未打开或无法访问,我将无法捕获异常我收到错误

org.hibernate.exception.JDBCConnectionException 

here name.save(user);

这里 name.save(user);

is hibernate command that executes sql command

是执行 sql 命令的休眠命令

how to catch this type of exceptions

如何捕捉这种类型的异常

i am getting errors

我收到错误

Unreachable catch block for JDBCConnectionException.This exception is never thrown from the try statement body

JDBCConnectionException 的无法访问的 catch 块。这个异常永远不会从 try 语句体中抛出

Unreachable catch block for SQLException. This exception is never thrown from the try statement body

SQLException 的无法访问的 catch 块。这个异常永远不会从 try 语句体中抛出

mycode:

我的代码:

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){}

回答by Esty

Use JDBCConnectionExceptionfor connection related exceptions and ConstraintViolationExceptionfor constrain violation. You should use other exceptions as per your requirement. See enter link description here

使用JDBCConnectionException处理与连接相关的异常,使用ConstraintViolationException处理违反约束的情况。您应该根据您的要求使用其他例外。请参阅在此处输入链接说明

回答by ArunDhwaj IIITH

In Addition to @Tanjim Rahman,

除了@Tanjim Rahman,

The Code Snippet

代码片段

In UserDAOImpl.java

在 UserDAOImpl.java 中

Use ConstraintViolationException to catch the duplicate Entry

使用 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;
}

回答by wiretext

you may only catch exceptions that are thrown at you directly (at least for checked exceptions...). If you really want to handle this specific error situation in any reasonable way, there is the possibility to catch what is thrown at you and inspect the cause of the exception provided

您只能捕获直接向您抛出的异常(至少对于已检查的异常...)。如果您真的想以任何合理的方式处理这种特定的错误情况,则有可能捕获向您抛出的内容并检查所提供的异常的原因

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
    }
}

Credit Oracle Community

信用甲骨文社区