views:

28

answers:

1

I am new in hibernate,after read the hibernate api and tutorial,it seems that the session should cloesd when not used.

Like this:

Session sess=getSession();
Transcration tx=sess.beginTranscration();
//do something using teh session
sess.save(obj);
tx.commit();
sess.close;

I have no question when using it in a standlone application. However I am not sure when using in the web app.

For exmaple, I have a servlet:TestServlet to recieve the parameters from the client,then I call a Manager to query something according to the parameters: just like this:

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.
  }
}

Shoule I close the session in the query method?

Since someone tell me the session in hibernate just like the connection in jdbc,so open and close it so frequently is the correct way?

BTW,does the tx.commit() is required each time?

Also what's the thread problem about using session in servlet,since I saw the session is not thread safe in api.

A: 
Pascal Thivent
Thanks for your reply. Now I decide create a static class HibernateUtil which can return session by getCurrentSession(),then I call the HibernateUtil to get a session in other place. Is this right?
hguser
Also,**each session per requset**, I wonder if this will cause low perfromance, since when I did not use hibernate, I will use a ConnectionPool.
hguser
@hguser: If you're not using EJB or Spring, then yes, go for a HibernateUtils class. And no, obtaining a Session is not an expensive operation and is not a performance concern, it's not worse than obtaining a connection from the pool.
Pascal Thivent
Thanks :) A related question: how should I know about jdbc,and sql to use and learn hibernate better?
hguser

related questions