JDBCConnectionException

JDBCConnectionException

有时下面代码中的get方法将捕获代码下面显示的JDBCConnectionException。有人能解释为什么get方法会导致抛出这个异常吗?
HibernateUtils.java

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"));
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.release_mode",

ConnectionReleaseMode.AFTER_TRANSACTION.name());

org.hibernate.cfg.Configuration config = new org.hibernate.cfg.Configuration()
               .addProperties(prop)
               .addAnnotatedClass(Account.class);


public static Object get(Class<?> clazz, Integer id) {
    try {
        Session session = openSession();
        Object obj = get(clazz, id, session);
        session.close();
        return obj;
    } catch(Exception ex) {
        System.out.println(ex);
    }
        return null;
}

JDBC连接异常:
org.hibernate.exception.JDBCConnectionException: Communications link failure
The last packet successfully received from the server was 82.116 milliseconds ago.
The last packet sent successfully to the server was 2 milliseconds ago.

最佳答案

代码捕获JDBCConnectionException的原因是连接池。
您可以在hibenate中使用c3p0配置。
配置文件:

<!-- Employee DB data source. -->
<bean id="employeeDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.employee_db_url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
    <property name="minPoolSize" value="${jdbc.minPoolSize}" />
    <property name="maxStatements" value="${jdbc.maxStatements}" />
    <property name="testConnectionOnCheckout" value="${jdbc.testConnection}" />
</bean>

数据库配置:也可以直接放入hibernate文件中。
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.employee_db_url=jdbc:mysql://localhost:3306/employee
jdbc.username=root
jdbc.password=root
jdbc.maxPoolSize=50
jdbc.minPoolSize=10
jdbc.maxStatements=100
jdbc.testConnection=true

您还必须在c3p0中添加pom.xml依赖项。

07-26 02:00