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.