Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session Management with Java Hibernate

Tags:

java

hibernate

I have a Hibernate-based platform, built from stateless servlets (one is used to register a user and the rest to query the db).

I'm using Hibernate's sessions as follows:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
if ((null == session) || (session.isOpen() == false)) {
  session = HibernateUtil.getSessionFactory().openSession();
}

Currently I do not close the session at the end of the servlet in order to avoid openSession() call (trying to use opened sessions if possible).

What's the best practice ? when am I supposed to close these sessions ?

Can you please give an example ?

Thanks in advance !

like image 586
Ohad Greenshpan Avatar asked Feb 20 '12 20:02

Ohad Greenshpan


People also ask

What is Session management in hibernate?

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

What is Session in hibernate with example?

The Session interface is the main tool used to communicate with Hibernate. It provides an API enabling us to create, read, update, and delete persistent objects. The session has a simple lifecycle. We open it, perform some operations, and then close it.

What is Session and SessionFactory in hibernate?

SessionFactory is a factory class for Session objects. It is available for the whole application while a Session is only available for particular transaction. Session is short-lived while SessionFactory objects are long-lived. SessionFactory provides a second level cache and Session provides a first level cache.


1 Answers

The best practice is in most cases session-per-request. That is, open a session in the beginning of handling a request, and close it in the end. You can do that in a Servlet Filter, for example.

Having one session for the entire application is bad, because it will accumulate a lot of entities in its 1st level cache, which is a memory leak. It may also produce undeterministic results when multiple clients use it at the same time.

Your code, however, is not using one session for the entire application - it is using the "current session" concept, which opens a session and stores it in a context (a ThreadLocal for example). But if you don't close it, it will stay there forever. Plus, it will cause the same problems as described above, because threads are reused in a web application, and a new request will get an old, unclosed session at some point.

like image 176
Bozho Avatar answered Oct 31 '22 23:10

Bozho