如何检查或知道是否正确建立了与远程数据库的连接,如果没有切换另一个数据库。
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>
我可以连接到我的数据库,但是如果服务器出现故障我如何确定我是否已连接?
答案 0 :(得分:1)
Session session = factory.openSession();
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
//You got a connection
}
});
答案 1 :(得分:0)
您可以尝试连接级别方法isValid()。