方法有时会捕获一个org.hibernate.exception.JDBCConnectionException,为什么?

时间:2015-10-27 16:03:46

标签: java mysql hibernate

有时,下面代码中的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;
}

JDBCConnectionException:

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.

1 个答案:

答案 0 :(得分:2)

您的代码捕获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依赖项。