0

我如何检查或知道与远程数据库的连接是否正确建立,如果不切换另一个数据库。

private static SessionFactory configureSessionFactory(String name) throws HibernateException 
    {
        ServiceRegistry serviceRegistry;
        Configuration configuration = new Configuration();
        configuration.configure(name);
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        SessionFactory factory;
        factory = configuration.buildSessionFactory(serviceRegistry);
        return factory;
    }

是我用来构建我的 SessionFactory 的方法。

这是我的配置:

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">
    jdbc:h2:tcp://193.168.1.70/history
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">false</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="PriceBar.hbm.xml"/>
</session-factory>
</hibernate-configuration>

我可以连接到我的数据库,但是如果服务器出现故障,我如何确定我是否已连接?

4

2 回答 2

1
Session session = factory.openSession();
session.doWork(new Work() {
    @Override
    public void execute(Connection connection) throws SQLException {
        //You got a connection
    }
});
于 2015-03-18T06:56:49.907 回答
0

有一个连接级别的方法 isValid() 你可以试试。

于 2013-07-31T08:29:17.373 回答