1

我面临一个问题 - 在我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>
4

0 回答 0