Control the hibernate session(when to close it manually)

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

It should be closed when you're done with (but this can be done automatically for you as we'll see).

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

Well, as explained in the section 11.1.1. Unit of work of the documentation, the most common pattern in a multi-user client/server application is session-per-request.

For example, 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 (...) Should I close the session in the query method?

It all depends on how you obtain the session.

  • if you use sessionFactory.getCurrentSession(), you'll obtain a "current session" which is bound to the lifecycle of the transaction and will be automatically flushed and closed when the transaction ends (commit or rollback).
  • if you decide to use sessionFactory.openSession(), you'll have to manage the session yourself and to flush and close it "manually".

To implement a session-per-request pattern, prefer the first approach (much easier and less verbose). Use the second approach to implement long conversations.

The wiki page Sessions and transactions is a good complement to the documentation on this topic.

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

You might want to read Non-transactional data access and the auto-commit mode to clarify a few things but, to put it simply, your Hibernate code has to be executed within a transaction and I'd suggest to use explicit transaction boundaries (i.e. explicit beginTransaction and commit).

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

Just don't make it an instance variable of the Servlet and you won't have any problem.

References

  • Hibernate Core 3.3 Reference Guide
    • Chapter 11. Transactions and Concurrency
  • Hibernate wiki
    • Sessions and transactions
    • Non-transactional data access and the auto-commit mode

If you are getting session through sessionFactory.openSession() then you have to close it externally. Opened session for unintended period can cause the data leaks. Plus it can give invitation to Web App security threat.