当前位置: 首页 > 知识库问答 >
问题:

组织。冬眠例外JDBCConnectionException:打开转换时无法打开连接

曾翰飞
2023-03-14

我正在使用Hibernate、Java和MySQL以及一个多线程应用程序,当我试图打开一个事务时,有时会抛出以下异常。

冬眠动物。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

连接打开,有时会出现此错误。为什么?

共有1个答案

孙修德
2023-03-14

这是由一个工人来管理数据库连接修复的

 类似资料:
  • 我在本地机器上安装了一个mysql实例,并将其与GAE上的java hibernate应用程序一起使用。这是完美的工作,但从下午开始,它已经开始给我下面给出的错误。请帮我弄清楚如何解决这个问题。我被卡住了,无法在没有任何db事务的情况下继续使用代码。谢谢

  • 我已经为这个问题挣扎了一段时间了。我有一个使用Struts2、spring和Hibernate的基于web的应用程序。我使用Spring将struts动作、业务和dao层连接在一起。我正在使用JMeter对应用程序进行负载测试。当我模拟1个用户反复发送get请求时,应用程序运行良好,没有问题。但是,当我再添加几个用户时,过了一段时间后,我得到以下错误: 所以,我假设这是一个连接泄漏,但是当我模拟一

  • 我需要你帮我把冬眠映射成一对多我不知道为什么这是错的 另一类: 映射 另一个映射: Hibernate配置 这就是错误: 如果有人能帮我,我非常感激,谢谢!

  • 我正在使用spring hibernate开发一个应用程序,如果我使用的是199.892.2.345这样的数据库,我就可以连接到该数据库并执行cud操作,但是如果我将其更改为spring config中的Vinayaka.cloudapp.net,111这样的云数据库,我会得到下面的错误,下面是我正在使用的spring config文件, 错误

  • 我试图将Spring MVC与Hibernate(即HibernateTemplate)集成,但却被这个ClassCastException ie org所困扰。springframework。orm。hibernate4.LocalSessionFactoryBean无法转换为org。冬眠SessionFactory。我正在使用Hibernate-4(ie-org.springframework

  • 我正在尝试从当前用户那里获取特定租金的列表。 控制器中的代码: account\u id是外键。 运行后,我发现错误: 我做错了什么?