Hi all, I am reading the Hibernaate documentation. I am focusing on the creation of the session object.
1. As far as I understand it I first call the following code in a start up servlet. SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
2. Then I use the HibernateUtil.class found in the Hibernate documentation. Session session = HibernateUtil.currentSession();
My question is, if i use this technique, is a new instance of the Session object created for each servlet in which it is called? For example, in Login.java servlet I create a new Session object using HibernateUtil.java. Is this session object shared by all threads of Login.java or a Session object is created for each thread of Login.java
If someone could please explain how it works I would really appreciate it.
The current session is stored as a ThreadLocal variable (variable having a Thread level scope) so it can be shared by all objects that need to use it in the scope of that same request
When a new request arrives at the Login servlet, the servlet engine will create a new thread. Since it is a new thread the static class variable referencing the session will be null and the call to currentSession() will create a new session.
Originally posted by Kevin Arouza: When a new request arrives at the Login servlet, the servlet engine will create a new thread. Since it is a new thread the static class variable referencing the session will be null and the call to currentSession() will create a new session.
Just a point of clarification: the static variable "session" is initialized to an instance of ThreadLocal; it can't be null, otherwise you'll get a NullPointerException. What is null is the value returned by the ThreadLocal instance's get() method when it is accessed by a new thread. (This may well be what you meant but it's not exactly how your reply reads)