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 ?
It represents the classname of a custom ConnectionProvider which provides JDBC connections to Hibernate. It is used to set the JDBC transaction isolation level. It enables auto-commit for JDBC pooled connections.
Hibernate integration with Servlet and JSP :These data we will collect in servlet and finally insert these data into Database by using hibernate. For creating the web application, we are using JSP for presentation logic, Servlet class for controller layer and DAO class for database access codes.
As we create the simple application in hibernate, we don't need to perform any extra operations in hibernate for creating web application. In such case, we are getting the value from the user using the JSP file.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With