gpt4 book ai didi

java - 克服 Hibernate 5 连接限制

转载 作者:行者123 更新时间:2023-12-01 21:18:36 26 4
gpt4 key购买 nike

我正在制作一个与数据库通信的 RESTful 服务,使用 Hibernate 作为 ORM。

我面临的问题是 Hibernate 的连接池限制,每当我达到限制时就会抛出异常。

Exception in thread "main" org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available!
<小时/>

1)我尝试在 hibernate.cfg.xml 中设置最大池大小

<property name="connection.pool_size">10</property>

2)我尝试过获取当前连接,而不是每次都打开一个新 session

public static Session getCurrentSession(){
try{
return sessionFactory.getCurrentSession();
}
catch(Exception e){
try {
return sessionFactory.openSession();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
<小时/>

我最终总是会达到极限

有办法完全克服这个问题吗?

最佳答案

2) I have tried instead of opening a new Session every time, ...

我假设在您常用的代码中,您将像这样打开 session :

Session session = sessionFactory.openSession();

您报告的异常通常在您未关闭 session 时发生。但是,即使您似乎已经关闭了 session,但也有可能发生一些异常,不允许控件访问 session.close()陈述。

Session session = sessionFactory.openSession();
statement1;
statement2; // <-- Exception occurs here
statement3;
session.close();// <-- because of above Exception, your control never reaches here.

因此,这种情况下的最佳实践是在像这样的finally block 中编写session.close()

Session session;
try {
session = sessionFactory.openSession();
statement1;
statement2; // <-- Exception occurs here
statement3;
}
finally {
session.close();// <-- although there's an exception above, your control won't leave without executing this statement.
}
<小时/>

如果您使用的是 Java 7 及更高版本,那么您还可以使用尝试使用资源oracle doc

try (Session session = sessionFactory.openSession()) {
statement1;
statement2;
statement3;
}

关于java - 克服 Hibernate 5 连接限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507622/

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