Hibernate throw" org.hibernate.exception.JDBCConnectionException:无法打开连接"随机在多线程应用程序中

时间:2015-11-02 14:49:08

标签: java multithreading hibernate heroku

public class HibernateUtil {

private static SessionFactory INSTANCE_SESSION_FACTORY = null;

public enum Common {
    SUCCESS, ROLLBACK
}

private synchronized static void createSessionFactory() {
    try {
        if (INSTANCE_SESSION_FACTORY != null) {
            return;
        }
        ResourceBundle rb = ResourceBundle.getBundle("application");
        Integer environment = Integer.valueOf(rb.getString("environment"));

        Properties prop = new Properties();

        switch (environment) {
        /* LOCAL */
        case 1:
            prop.setProperty("hibernate.connection.driver_class", rb.getString("hibernate.driver.class.name"));
            prop.setProperty("hibernate.connection.url", rb.getString("hibernate.db.uri"));
            prop.setProperty("hibernate.connection.username", rb.getString("hibernate.db.username"));
            prop.setProperty("hibernate.connection.password", rb.getString("hibernate.db.password"));
            break;
        default:
            throw new ConfigurationException(environment == null ? "No environment added in application.properties"
                    : "Wrong environment added in application.properties");
        }

        prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        prop.setProperty("hibernate.show_sql", "true");
        prop.setProperty("hibernate.hbm2ddl.auto", "update");
        prop.setProperty("hibernate.current_session_context_class", "thread");
        prop.setProperty("hibernate.connection.pool_size", "100");

        prop.setProperty("hibernate.c3p0.minPoolSize", "5");
        prop.setProperty("hibernate.c3p0.maxPoolSize", "100");
        prop.setProperty("hibernate.c3p0.initialPoolSize", "10");
        prop.setProperty("hibernate.c3p0.timeout", "1800");
        prop.setProperty("hibernate.c3p0.max_statements=", "50");

        org.hibernate.cfg.Configuration config = new org.hibernate.cfg.Configuration().addProperties(prop)
                .addAnnotatedClass(Account.class).addAnnotatedClass(InsynctiveProperty.class)
        serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
        .buildServiceRegistry();
        INSTANCE_SESSION_FACTORY = config.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    if (INSTANCE_SESSION_FACTORY == null) {
        createSessionFactory();
    }
    return INSTANCE_SESSION_FACTORY;
}

public static Session getCurrentSession() {
    return getSessionFactory().getCurrentSession();
}

public static Session openSession() {
    return getSessionFactory().openSession();
}

public static void closeCurrentSession() {
    getSessionFactory().getCurrentSession().close();
}

public synchronized static Object get(Class<?> clazz, Integer id) {
    Session session = getCurrentSession();
    final Transaction transaction = session.beginTransaction();
    try {
        Object obj = session.get(clazz, id);
        transaction.commit();
        return obj;
    } catch (RuntimeException ex) {
        System.out.println(ex);
        transaction.rollback();
        throw ex;
    } finally {

    }
}

public Common save(Object object) {
    Session session = openCurrentSession();
    Transaction transaction = null;
    Common result = null;
    try {
        transaction = openTransaction(session);
        session.save(object);
        transaction.commit();
        result = Common.SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();
        if (transaction != null) {
            transaction.rollback();
        }
        result = Common.ROLLBACK;
    } finally {
        session.close();
    }

    return result;
}

public Common update(Object object) {
    Session session = openCurrentSession();
    Transaction transaction = null;
    Common result;

    try {
        transaction = openTransaction(session);
        session.update(object);
        transaction.commit();
        result = Common.SUCCESS;
    } catch (Exception e) {
        e.printStackTrace();

        if (transaction != null) {
            transaction.rollback();
        }
        result = Common.ROLLBACK;
    } finally {
        session.close();
    }
    return result;
}

public Session openCurrentSession() {
    return getSessionFactory().openSession();
}

public Transaction openTransaction(Session session) {
    return session.beginTransaction();
}
}

有时候当我使用其中一个方法时,我会发现这个错误:

  

org.hibernate.exception.JDBCConnectionException:无法打开连接

     

[org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131),   org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49),   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125),   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110),   org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304),   org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169),   org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67),   org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160),   org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396),   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62),   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),   java.lang.reflect.Method.invoke(Method.java:483),   org.hibernate.context.internal.ThreadLocalSessionContext $ TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)   com.sun.proxy。$ Proxy66.beginTransaction(未知来源),   insynctive.utils.HibernateUtil.get(HibernateUtil.java:123),   insynctive.tests.TestMachine.tearUp(TestMachine.java:104),   insynctive.tests.PersonFileTest.tearUp(PersonFileTest.java:52),   sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62),   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),   java.lang.reflect.Method.invoke(Method.java:483),   org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85),   org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:517),   org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213),   org.testng.internal.Invoker.invokeConfigurations(Invoker.java:140),   org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:170),   org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:104),   org.testng.TestRunner.privateRun(TestRunner.java:771),   org.testng.TestRunner.run(TestRunner.java:621),   org.testng.SuiteRunner.runTest(SuiteRunner.java:357),   org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352),   org.testng.SuiteRunner.privateRun(SuiteRunner.java:310),   org.testng.SuiteRunner.run(SuiteRunner.java:259),   org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52),   org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86),   org.testng.TestNG.runSuitesSequentially(TestNG.java:1199),   org.testng.TestNG.runSuitesLocally(TestNG.java:1124),   org.testng.TestNG.run(TestNG.java:1032),   insynctive.runnable.RunnableTest.run(RunnableTest.java:15),   java.lang.Thread.run(Thread.java:745)]

SQLStateConversionDelegate.java:131

else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) {
                    return new JDBCConnectionException( message, sqlException, sql );

我需要重启池会话才能继续工作..

有什么想法吗? 我的应用程序是多线程应用程序,我抛出 6-10个线程

注意 当我使用本地数据库时,我使用Heroku DB(ClearDB MySQL)我无法重现此错误。

1 个答案:

答案 0 :(得分:2)

您已实施双重检查锁定模式。为了使其正常工作,您必须制作INSTANCE_SESSION_FACTORY变量volatile

请注意,这可能是也可能不是异常的原因,但它肯定是您代码中的错误。

更新:

您可能只是遇到汇总连接超时的情况。您可能想尝试启用c3p0的空闲连接检查(类似“idleConnectionTestPeriod = 300”)。