-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: HibernateUtil and ThreadLocal in Web applications
PostPosted: Fri Mar 11, 2005 2:33 pm 
Newbie

Joined: Tue Feb 22, 2005 4:10 pm
Posts: 19
Hi,

Why is the use of ThreadLocal even needed when the code that does the persistence is untimately invoked by something like a "get" method inside a servlet or say "execute" method inside an Action (Struts)?

Anything declared or invoked inside the servlet's method is thread-safe, isn't it?

So, if inside "execute" of my Action (in Struts) I have somethig like this:

Code:
{
....

   // Retrieve SessionFactory from ServletContext
      ServletContext servletContext = this.getServlet().getServletContext();
      SessionFactory sessionFactory = (SessionFactory) servletContext.getAttribute("sessionFactory");
     
      // Open session
      Session session = sessionFactory.openSession();
      Transaction tx = session.beginTransaction();
     
      Messages message = new Messages();
      message.setMessageText("Hello World!");
      session.save(message);
      tx.commit();
      session.close();

...
}


Why would I need ThreadLocal?

Note that I have a ServletContextListener registered in my web.xml and contextInitialized() method does this:
Code:
{
Configuration configuration = new Configuration();
         SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
         
         // Save SessionFactory into ServletContext
         sce.getServletContext().setAttribute("sessionFactory", sessionFactory);
}


Thanks,
NG.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Mar 11, 2005 2:48 pm 
Newbie

Joined: Tue Feb 22, 2005 4:10 pm
Posts: 19
Never mind. I am jumping ahead of myself. It's actually explained in the book.

Sorry.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.