我遇到了问题 - 在我的应用程序中,我使用hibernate
来访问数据库。看起来一切正常,但是当我不使用应用程序一段时间(〜天或更长时间)时,它会在尝试访问数据库时产生错误。我认为,这是因为连接已经关闭,因为我通过一个singleton
的类打开它。
这个类的代码:
package cz.cvut.fit.genepi.utils;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// TODO: Auto-generated Javadoc
/*
* class that handles connection with the database via hibernate
*/
/**
* The Class HibernateUtil.
*/
public class HibernateUtil {
/** The Constant sessionFactory. */
private static final SessionFactory sessionFactory = buildSessionFactory();
/**
* Builds the session factory.
*
* @return the session factory
*/
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* Gets the session factory.
*
* @return the session factory
*/
public static SessionFactory getSessionFactory() {
if (sessionFactory==null)
buildSessionFactory();
return sessionFactory;
}
/**
* Shutdown.
*/
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
有没有办法,怎么检查,如果连接仍然打开,那么我可以重新打开它?
getSessionFactory().isClosed()
我正在寻找什么?那么我就可以这样写:
public static SessionFactory getSessionFactory() {
if (sessionFactory==null || getSessionFactory().isClosed())
buildSessionFactory();
return sessionFactory;
}
我知道我可以简单地尝试一下,但问题是,生成此错误需要相当长的时间。
如果你不认为这可能是问题的根源,那么我在这里附上堆栈跟踪: http://pastebin.com/6Yigjgt8
hibernate.cfg.xml
:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:2080/genepi</property-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="./models/Patient.hbm.xml"></mapping>
<mapping resource="./models/Contact.hbm.xml"></mapping>
<mapping resource="./models/Anamnesis.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>