MySQLNonTransientConnectionException:连接关闭后不允许任何操作

时间:2015-03-12 18:43:41

标签: java mysql hibernate c3p0

我希望有人可以帮助我。我的数据库连接一直关闭,不会重新打开,因此我不得不每隔几个小时重新启动一次应用程序。

我在这里看到了其他答案并试图实施它们但它们似乎没有任何区别。我的JDBC url有autoReconnect = true,我正在使用hibernate和c3p0连接池。

任何帮助都会很棒!

hibernate.cfg.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/devenv38?autoReconnect=true</property>
    <property name="hibernate.connection.username">devenv38</property>
    <property name="hibernate.connection.password">devenv38</property>
    <property name="hibernate.connection.autoReconnect">true</property>
    <property name="hibernate.connection.autoReconnectForPools">true</property>
    <property name="connection.is-connection-validation-required">true</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- Use the C3P0 connection pool provider -->
    <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
    <property name="c3p0.acquire_increment">5</property>
    <property name="c3p0.max_size">500</property>
    <property name="c3p0.max_statements">0</property>
    <property name="c3p0.idleConnectionTestPeriod">120</property>
    <property name="c3p0.initialPoolSize">25</property>
    <property name="c3p0.min_size">25</property>
    <property name="c3p0.numHelperThreads">15</property>
    <property name="c3p0.timeout">0</property> <!-- seconds -->

    <property name="hibernate.show_sql">false</property> 
    <property name="hibernate.format_sql">false</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <!-- resources -->
    <mapping class="entities.Story" />
    <mapping class="entities.User" />
</session-factory>

数据库连接类

public class DatabaseConnection
{

static SessionFactory sf;

private DatabaseConnection()
{
    Configuration configuration = new Configuration();
    configuration.configure();
    ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()).buildServiceRegistry();
    sf = configuration.buildSessionFactory(sr);
}

public static Session getSession()
{
    if (sf == null)
    {
        new DatabaseConnection();
    }

    return sf.openSession();
}
}

使用示例

    Session session = DatabaseConnection.getSession();
    Transaction txn = session.beginTransaction();
    User user = new User();
    user.setUsername("JUNIT USER 1");
    user.setEmail("test@test.com");
    user.setPassword("Test Password");
    session.save(user);
    txn.commit();

0 个答案:

没有答案