如何检查该数据库是否可用,我可以在sessionFactory = configuration.buildSessionFactory(serviceRegistry)之后运行查询

时间:2014-08-06 13:55:46

标签: java hibernate

这是我的初始化SessionFactory

的代码
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://" + host + ":" + port + "/" + dbName);
    configuration.setProperty("hibernate.connection.username", user);
    configuration.setProperty("hibernate.connection.password", pass);
    configuration.setProperty("hibernate.c3p0.min_size", minConns);
    configuration.setProperty("hibernate.c3p0.max_size", maxConns);
    configuration.setProperty("hibernate.c3p0.max_statements", "50");
    configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.pool_size", "1");
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
    configuration.setProperty("hibernate.current_session_context_class", "thread");
    configuration.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider");
    configuration.setProperty("hibernate.show_sql", "false");
    configuration.addResource("TransactionBean.hbm.xml");
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

我在没有SQL数据库的机器上运行此代码,而且我所拥有的只是:

16:27:24,719  WARN BasicResourcePool:1851 - com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@62455eba 
-- Acquisition Attempt Failed!!! Clearing pending acquires. 
While trying to acquire a needed new resource, 
we failed to succeed more than the maximum number of
allowed acquisition attempts (30). 
Last acquisition attempt exception: 
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

那只是警告信息,没有例外。 我需要验证连接是否已成功建立,我可以继续。否则我需要更改参数并尝试连接到其他数据库。

1 个答案:

答案 0 :(得分:0)

我想我应该看看这里。 http://www.mchange.com/projects/c3p0/index.html#configuring_connection_testing 我试图实现它,但验证不起作用。这是另一个问题。