draca
draca

Reputation: 1399

How to initialize hibernate session from within servlet?

I'm learning java servlets and hibernate. I have separate working examples of each and am now trying to merge the hibernate example into an http servlet.

My simple hibernate sample starts with this code

factory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = factory.openSession();

When the http servlet is called via an http get, I understand it's calling the constructor first, then the doGet method.

Now my question (please be easy on me as I'm a newbie here): what is the accepted way to call the hibernate initialization code from the servlet? Do I put the above initialization code in the constructor method?

Upvotes: 3

Views: 12206

Answers (3)

orikare
orikare

Reputation: 7

Try with servlet listener .

Upvotes: -4

Mitul Maheshwari
Mitul Maheshwari

Reputation: 2647

Create a one Separate class for Hibernet Connection.

    package com.abc.xyz.dao;

    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;


    public class HibernateUtil {

      private static final SessionFactory sessionFactory = buildSessionFactory();

      @SuppressWarnings("deprecation")
    private static SessionFactory buildSessionFactory() {
        try {
          // Create the SessionFactory from Annotation
          return new AnnotationConfiguration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
          // Make sure you log the exception, as it might be swallowed
          System.err.println("Initial SessionFactory creation failed." + ex);
          throw new ExceptionInInitializerError(ex);
        }
      }

      public static SessionFactory getSessionFactory() {
        return sessionFactory;
      }
    }

On Server Side get Connection for that

        Session session=null;

     try {
        session =HibernateUtil.getSessionFactory().openSession();



    } catch (HibernateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally
    {
        session.close();
    }

Upvotes: 3

Bnrdo
Bnrdo

Reputation: 5474

There are a lot of ways how to manage hibernate session. One of the most common way is using HibernateUtil class. The usual implementation is, the SessionFactory is statically initialized, which means, the initialization will only be done once (when the class is loaded). Then it exposes a static method for getting the built SessionFactory instance. Here is an example of implementation from dzone.

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

For opening and closing of session, it is usually treated as a one unit with the request processing, so you call HibernateUtil.getSessionFactory().openSession() in the beginning of doGet or doPost and ensure to close the session before the end of the method.

Upvotes: 8

Related Questions