Hibernate + C3P0如何拦截数据库是不可达的?

时间:2014-06-17 12:26:47

标签: hibernate c3p0

大家下午好,

我的问题可能很简单,但我无法自行解决。

我有一个带有Hibernate + C3P0连接池的j2EE应用程序。

我有类似的东西来创建一个会话工厂:

    Configuration conf = new Configuration();
    conf.setProperty("hibernate.connection.username","root");
    conf.setProperty("hibernate.connection.password","root");
    conf.setProperty("hibernate.connection.url",dbURL);

    SessionFactory sessionFactory = conf.buildSessionFactory();

一切正常。

如果我关闭MySQL并重启应用程序,我会收到以下消息:

com.mchange.v2.resourcepool.CannotAcquireResourceException:ResourcePool无法从其主要工厂或来源获取资源

但是我无法拦截此例外。

问题是: 我怎么才能意识到此时数据库无法访问?

谢谢。

1 个答案:

答案 0 :(得分:0)

请配置连接测试,然后c3p0将自我修复。

请参阅http://www.mchange.com/projects/c3p0/#configuring_connection_testing

注意:您可能正在使用c3p0-0.9.2.1,它尚不支持Connection.isValid()。因此,请为您的测试设置一个有效的preferredTestQuery(通过hibernate,hibernate.c3p0.preferredTestQuery)。对于MySQL,SELECT 1通常会这样做。