Wednesday, April 6, 2011

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 ?

From stackoverflow
  • 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.

    blackliteon : What DBCP You are using ? I see 2 options: cp3o & tomcat CP.
    blackliteon : About MVC: I use GWT as frontend, so I dont need to use MVC
    whaley : 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.
    Jack Leow : @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.
    blackliteon : @Javk Leow: Tomcat 5.5 DBCP documentation: http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html
  • Use the Open Session in View pattern (see the filter implementation).

0 comments:

Post a Comment