What is the best place in servlet for Hibernate code that returns HibernateSessionFactory ?
I saw many examples: ones put db connection in service methods. Others – use smth like HibernateUtil (Singleton) that returns HibernateSessionFactory.
I don’t know is it safe to use HibernateUtil in multithreaded Servlets ?
Usually, you should use an MVC framework in favor of Servlets directly, but that’s not your question, and I’m going to assume you have a good reason to be implementing your own Servlets. On to the answer…
Per this – https://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html:
and
So it’s OK to share an instance of
SessionFactorys.In fact, from my experience, your HibernateUtil approach is the better approach, as SessionFactory creation can be very expensive.