我是hibernate的新手,在阅读了hibernate api和教程后,看来会话应该在不使用时关闭.
像这样:
Session sess=getSession();
Transcration tx=sess.beginTranscration();
//do something using teh session
sess.save(obj);
tx.commit();
sess.close;
Run Code Online (Sandbox Code Playgroud)
在独立应用程序中使用它时我毫无疑问.但是我不确定何时在网络应用中使用.
例如,我有一个servlet:TestServlet从客户端接收参数,然后我调用Manager来根据参数查询,就像这样:
class TestServlet{
doGet(HttpServletRequset,httpServletResponse){
String para1=request.getParam...();
String para2=.....
new Manager().query(para1,para2);
}
}
class Manager{
public String query(String pa1,String pa2){
Session=....// get the session
//do query using para1 and 1
session.close() //Here, I wonder if I should close it.
}
}
Run Code Online (Sandbox Code Playgroud)
我应该在查询方法中关闭会话吗?
因为有人告诉我,hibernate中的会话就像jdbc中的连接一样.那么频繁打开和关闭它是正确的方法吗?
顺便说一句,每次都需要tx.commit()吗?
还有什么是在servlet中使用session的线程问题,因为我看到会话在api中不是线程安全的.