2013-05-09 54 views
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> 

我可以連接到我的數據庫,但如何確定服務器出現故障,如果我有聯繫嗎?

回答

0

有一個連接級別的方法isValid(),你可以嘗試。

1
Session session = factory.openSession(); 
session.doWork(new Work() { 
    @Override 
    public void execute(Connection connection) throws SQLException { 
     //You got a connection 
    } 
});