Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database connection via Hibernate in servlets

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 ?

like image 362
dmitrynikolaev Avatar asked Mar 12 '10 11:03

dmitrynikolaev


People also ask

How does Hibernate connect to database?

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.

Can we use Hibernate with servlet?

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.

Can we use Hibernate with JSP Servlet?

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.


2 Answers

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 a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment.

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.

like image 132
Jack Leow Avatar answered Sep 30 '22 06:09

Jack Leow


Use the Open Session in View pattern (see the filter implementation).

like image 27
Pascal Thivent Avatar answered Sep 30 '22 05:09

Pascal Thivent