Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does HibernateUtil work?

 
david allen
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

David
 
Jack Wiesenthaler
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Junilu Lacar
Bartender
Pie
Posts: 8790
81
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Jack Wiesenthaler
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Junilu, yeah it was a bit unclear.. I meant the actual value itself returned by get()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic