views:

301

answers:

2

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 ?

+5  A: 

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.

Jack Leow
blackliteon
About MVC: I use GWT as frontend, so I dont need to use MVC
blackliteon
just because GWT is a front end doesn't mean you should eschew using MVC as a pattern on the server side. Servlets are really best served as a Controller. Your servlets really ought to be delegating data access to another set of classes of yours that use hibernate. Your servlets should be completely agnostic to the fact that hibernate even exists.
whaley
@blackliteon I'd recommend setting up data sources within your servlet container (say Tomcat), and accessing it via JNDI. You can find some examples here - http://tomcat.apache.org/tomcat-4.1-doc/jndi-datasource-examples-howto.html
Jack Leow
Also, I agree with whaley, your servlets (I assume these are GWT RPC servlets) should serve as "controllers". Your Hibernate stuff should be hidden behind DAOs, and ideally, you'd have a layer (sometimes called "managers" or "facades") between the two.
Jack Leow
@Javk Leow: Tomcat 5.5 DBCP documentation: http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html
blackliteon
+1  A: 

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

Pascal Thivent