如何正确关闭和打开一个Hibernate会话? [英] How to properly close and open a Hibernate session?
问题描述
我有以下方法,每隔几秒钟插入一大批记录。在运行一段时间后,会出现如下错误:
I have the following method that inserts a large batch of records every few seconds. After some time of running I get errors like the following:
错误:通信链路故障
ERROR: Communications link failure
从服务器成功接收的最后一个数据包为523
毫秒前。最后一个成功发送到服务器的数据包是
8毫秒前。
The last packet successfully received from the server was 523 milliseconds ago. The last packet sent successfully to the server was 8 milliseconds ago.
2013年5月16日9:48:30 am com.mchange.v2.c3p0。 stmt.GooGooStatementCache
checkin语句INFO:签入语句有问题,丢弃。
May 16, 2013 9:48:30 AM com.mchange.v2.c3p0.stmt.GooGooStatementCache checkinStatement INFO: Problem with checked-in Statement, discarding.
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed.
我用于打开和关闭连接的代码如下:
The code I use to open and close connections is the following:
public DataControllerImp() {
session = HibernateUtil.getSessionFactory().openSession();
}
@Override
public void saveMessage(ArrayList<Message> messages) {
Transaction tx = session.beginTransaction();
for (int i = 0; i < mesages.size(); i++) {
Message message = messages.get(i);
try {
session.save(message);
if (i % 75 == 0) {
// flush a batch of inserts and release memory:
session.flush();
session.clear();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
session.close();
}
}
tx.commit();
}
我也使用c3p0连接池。我的配置如下:
I am also using c3p0 connection pooling. My configuration looks like:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.min_size">3</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.acquireRetryAttempts">1</property>
<property name="hibernate.c3p0.acquireRetryDelay">250</property>
我打开和关闭连接不正确吗?
Am I opening and closing the connections incorrectly? Please let me know what I can change to stop from receiving this error and halting my program.
推荐答案
Transaction tx = session.beginTransaction();
try {
for (int i = 0; i < mesages.size(); i++) {
Message message = messages.get(i);
session.save(message);
if (i % 75 == 0) {
// flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
tx.commit();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
tx.rollBack();
}finally{
session.close();
}
}
这篇关于如何正确关闭和打开一个Hibernate会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!