Hibernate:通过java代码模拟testConnectionOnCheckout选项效果

时间:2011-11-11 14:46:15

标签: java hibernate

我正在使用Web应用程序,有时我遇到MySql连接问题。 使用Hibernate配置文件中的testConnectionOnCheckoutpreferredTestQuery选项,我解决了问题,我的应用程序现在还可以。

但是,为了获得更好的性能,我只想在我的应用程序中发生特定事件时获得此选项的效果。例如:

try {
    ...........
}
catch(Exception e) {
    // java code to obtain the same effect as
    // testConnectionOnCheckout option with "Select 1" query
}

我必须使用哪些Java代码?

1 个答案:

答案 0 :(得分:0)

回答这个问题的最好方法是在源头查找。因此,我鼓励您获取Hibernate的源代码并找到测试连接的代码。

但无论如何,这里有点简单

public static boolean checkConnection(String jdbcUrl, String user, String password){
    boolean result = false;
    try {
                Configuration config = new AnnotationConfiguration().configure();
                config.setProperty("hibernate.connection.url", jdbcUrl);
                config.setProperty("hibernate.connection.username", user);
                config.setProperty("hibernate.connection.password", password);
                sessionFactory = config.buildSessionFactory();
                Session session = sessionFactory.openSession();
                Assert.assertFalse(sesssion.connection.isReadOnly());
                result = true;
    } catch(Throwable ex) {
                return = false;
    }
    return result;
}