![](/img/trans.png)
[英]org.hibernate.exception.JDBCConnectionException: Could not open connection exception in MySQL
[英]Hibernate throw “org.hibernate.exception.JDBCConnectionException: Could not open connection” Randomly in a Multi-Thread application
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(本机方法),sun.reflect。 NativeMethodAccessorImpl.invoke(NativeMethodAcces sorImpl.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(本机方法),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.invokeCo nfigurations(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数据库(ClearDB MySQL),但无法重现此错误。
您已经实现了双重检查的锁定模式。 为了使其正常工作,必须使INSTANCE_SESSION_FACTORY
变量为volatile
。
注意,这可能是导致异常的原因,也可能不是异常的原因,但这肯定是代码中的错误。
更新:
您可能只是遇到池连接超时的情况。 您可能要尝试启用c3p0的空闲连接检查(类似于“ idleConnectionTestPeriod = 300”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.