【发布时间】:2016-01-29 18:28:17
【问题描述】:
我正在尝试将 Spring Boot 1.2.6 与 HibernateJpaAutoConfiguration 一起使用。效果很好;那就是它由 entityManager “神奇地”创建,并使用我的 spring.jpa.* 属性为我完成所有配置。
但是,如果出现数据库错误(无效凭据、数据库不可访问等),我找不到在启动时捕获 Hibernate 异常的干净方法。
我想我可以捕获所有的 BeanCreationException 并检查根本原因,但这似乎是一个 hack:
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 错误是什么(即:无效的凭据、未验证的数据库等)。
【问题讨论】:
标签: java spring hibernate spring-boot