gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:20:08 25 4
gpt4 key购买 nike

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

最佳答案

您的代码捕获 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

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

关于java - 方法有时会捕获一个 org.hibernate.exception.JDBCConnectionException,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33372827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com