hibernate怎么判断session是否关闭

2024-12-30 14:09:12
推荐回答(1个)
回答1:

hibernate判断session是否关闭的方法:
1、通常需要首先获得session:
public static Session getSession() {
Session session = threadLocal.get();
if(session == null){
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
2、从session中开启事务:
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();
}
}

3、关闭session,调用 session.close()。