在SpringBoot应用程序启动时捕获Hibernate异常?

时间:2015-10-29 14:37:26

标签: java spring hibernate spring-boot

我正在尝试将Spring Boot 1.2.6与HibernateJpaAutoConfiguration一起使用。它很棒;这就是它“神奇地”由entityManager创建,并使用我的spring.jpa。*属性为我开箱即用。

但是,如果出现数据库错误(凭据无效,数据库无法访问等),我无法找到一种在启动时捕获Hibernate异常的简洁方法。

我想我可以捕获所有BeanCreationException并检查根本原因,但这看起来很糟糕:

    ConfigurableApplicationContext context;
    try {
        SpringApplication app = new SpringApplication(Application.class);
        context = app.run(args);
    } catch (Exception e) {
        // check if it is a DB error.  
        if( ExceptionUtils.getRootCause(e) instanceof( HibernateException ) ){
            System.out.println( "You are having trouble with the DB: " + ExceptionUtils.getRootCauseMessage(e) );
        }
    }
    finally{
        // finished so close the context
        if( context != null )
            context.close();
    }

在不失去使用自动配置功能的情况下,是否有更清洁/更简洁的方法?另外,如果没有解析错误消息,是否有办法确定Hibernate / DB错误是什么(即:无效的信用证,DB未经验证等)。

1 个答案:

答案 0 :(得分:0)

Instead of catching a very generic HibernateException, you can try catching JDBCConnectionException. This is a subclass of HibernateException used for DB connection problems (including incorrect DB setup).

https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/exception/JDBCConnectionException.html

相关问题