3

I am using Hibernate 3 version for my Application .

While going through tutorials on Hibernate, I found out that, SessionFactory should be created only once for the application. So for this I have decided to use a static block inside a class and a static method to return this as shown.

public class SessionFactoryInitiliaztion {
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Exception x) {
            x.printStackTrace();
        }
    }

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

Where exactly do I need to close this sessionFactory object , so that it resales the memory ?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Pawan
  • 31,545
  • 102
  • 256
  • 434
  • You can take Spring into consideration. Also read http://stackoverflow.com/questions/8724259/spring-hibernate-session-lifecycle on session management with Spring and Hibernate. – d1e Jun 12 '12 at 11:20
  • Probably as long as the application is running else at exit. Can refer http://stackoverflow.com/a/4544053/366964 for more details. – Nayan Wadekar Jun 12 '12 at 11:20
  • Thanks , but i am not using Spring for this Application , its based on Servlets , JSP and Hibernate and MYSQL . – Pawan Jun 12 '12 at 11:21
  • With servlets, you best bet IMHO is to use a servlet context listener (http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html) to open the SessionFactory at app start time and close the SessionFactory at app shut down time. – Steve Ebersole Jun 12 '12 at 13:23

2 Answers2

5

I cannot think of any reason (offhand) why you would want to close the session factory while your application exists, so I wouldn't be too concerned about reclaiming the memory. I would just close it when your application is shutting down.

John Kane
  • 4,383
  • 1
  • 24
  • 42
  • 1
    You have misunderstood my question , i want to close it when the application exists , so can i do this inside servlet destroy method or is there any appropriate place for closing the Hibernate sessionFactory Object ?? . – Pawan Jun 12 '12 at 11:39
  • sorry, yes that is where you should close it, in destroy() – John Kane Jun 12 '12 at 11:50
  • 3
    Well doing it in a servlet destroy method assumes you have just a single servlet and it is not pooled. The better option is to use ServletContextListener – Steve Ebersole Jun 12 '12 at 13:26
  • Yeah your right, I shouldn't have assumed that that was how this was set up. – John Kane Jun 12 '12 at 13:27
0

This appears a bug, however with a "deprecated" configuration the sessionFactory closes correctly:

    Configuration configuration = new Configuration().configure();
    sessionFactory = configuration.buildSessionFactory();