我正在使用Hibernate,Java和MySQL以及一个多线程应用程序,当我尝试打开一个事务时,有时会抛出以下异常。
HibernateUtils.java
@ImportResource("classpath:application.properties")
public class HibernateUtil {
private static volatile 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.charSet", "UTF-8");
prop.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
prop.setProperty("hibernate.connection.pool_size", "10");
prop.setProperty("hibernate.c3p0.minPoolSize", "1");
prop.setProperty("hibernate.c3p0.maxPoolSize", "3");
prop.setProperty("hibernate.c3p0.initialPoolSize", "1");
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)
.addAnnotatedClass(CrossBrowserAccount.class).addAnnotatedClass(EmergencyContact.class)
.addAnnotatedClass(USAddress.class).addAnnotatedClass(CreatePersonForm.class)
.addAnnotatedClass(ParamObject.class).addAnnotatedClass(Test.class);
ServiceRegistryBuilder builder = new ServiceRegistryBuilder().applySettings(config.getProperties());
INSTANCE_SESSION_FACTORY = config.buildSessionFactory(builder.buildServiceRegistry());
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public synchronized static SessionFactory getSessionFactory() {
if (INSTANCE_SESSION_FACTORY == null) {
createSessionFactory();
}
return INSTANCE_SESSION_FACTORY;
}
public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
public static Session getCurrentSession() {
try{
Session session = getSessionFactory().getCurrentSession();
System.out.println("The session was opened.");
return session;
} catch(Exception ex){
ex.fillInStackTrace();
System.out.println("Problems on Open the session.");
throw ex;
}
}
public static void closeSession(Session session) {
// try{
// session.close();
// System.out.println("The Session is close.");
// } catch(Exception ex){
// ex.fillInStackTrace();
// System.out.println("Problems on clossing the session.");
// throw ex;
// }
}
public static Object get(Class<?> clazz, Integer id) {
Session session = getCurrentSession();
Transaction transaction = null;
Object obj = null;
try {
transaction = openTransaction(session);
obj = session.get(clazz, id);
transaction.commit();
return obj;
} catch (RuntimeException ex) {
if (transaction != null) {
transaction.rollback();
}
ex.printStackTrace();
throw ex;
} finally {
closeSession(session);
}
}
public Common save(Object object) {
Session session = getCurrentSession();
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 {
closeSession(session);
}
return result;
}
public Common update(Object object) {
Session session = getCurrentSession();
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 {
closeSession(session);
}
return result;
}
public static Transaction openTransaction(Session session) {
try {
return session.beginTransaction();
} catch(Exception ex){
ex.printStackTrace();
throw ex;
}
}
}
栈跟踪
org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at com.sun.proxy.$Proxy66.beginTransaction(Unknown Source)
at insynctive.utils.HibernateUtil.openTransaction(HibernateUtil.java:201)
at insynctive.utils.HibernateUtil.get(HibernateUtil.java:139)
at insynctive.tests.TestMachine.changeParamObject(TestMachine.java:368)
at insynctive.tests.LoadingTests.hrPeopleLoadingTest(LoadingTests.java:72)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:659)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:845)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1153)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:771)
at org.testng.TestRunner.run(TestRunner.java:621)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
at org.testng.SuiteRunner.run(SuiteRunner.java:259)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1199)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1032)
at insynctive.runnable.RunnableTest.run(RunnableTest.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
连接打开,有时会出现此错误。 为什么?的
答案 0 :(得分:0)
使用单个工作人员修复此问题以管理数据库连接