3

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?

2
  • You would typically do it in its init() method or within a ServletContextListener. Commented Feb 5, 2014 at 5:33
  • If you want the hibernate session object at the doGet or doPost method. you should create the session object at the init method. and declare the session object in class scope. Commented Feb 5, 2014 at 7:11

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I tried implementing this, but I get the error "tomcat7 at localhost failed to start" when calling openSession() in the doGet() because it seems that the SessionFactory initialization code in the HibernateUtil class is not being called. What am I doing wrong?
3

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();
    }

Comments

-4

Try with servlet listener .

1 Comment

Could you extend your answer a bit more please?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.