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 multithr开发者_如何学JAVAeaded 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:
Implementors must be threadsafe.
and
SessionFactorys
are immutable. The behaviour of aSessionFactory
is controlled by properties supplied at configuration time. These properties are defined onEnvironment
.
So it's OK to share an instance of SessionFactory
s.
In fact, from my experience, your HibernateUtil approach is the better approach, as SessionFactory creation can be very expensive.
Use the Open Session in View pattern (see the filter implementation).
精彩评论