1

I have HibernateUtil class and pack of entities, servlets and jsp. What should I add to my code or hibernate config file to start create all H2 tables(according to my entities) right after deployment my war file on Tomcat, before first call(in my case this is login)

public class HiberUtil {
private static final SessionFactory sFactory = configureSessionFactory();

private static SessionFactory configureSessionFactory() {
    Configuration cf = new Configuration();
    cf.configure("hibernate.cfg.xml");
    SessionFactory sf = cf.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cf.getProperties()).build());
    return sf;
}

public static SessionFactory getSessionFactory() {
    return sFactory;
}

public static void closeSessionFactory(){
    sFactory.close();
}

}

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • I believe the hbm2ddl-auto property is what you are looking for: http://stackoverflow.com/questions/438146/hibernate-hbm2ddl-auto-possible-values-and-what-they-do – Soggiorno Jan 24 '16 at 18:15

1 Answers1

1

Although it's better to use a container like Java EE or Spring, which manage resource automatically, you can still do it manually.

You need to add a listener in web.xml:

<listener>
    <listener-class>my.package.HibernateApplicationContextListener</listener-class>
</listener>

And then implement the listener as follows:

public class HibernateApplicationContextListener 
    implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        HiberUtil.getSessionFactory();
    }

    public void contextDestroyed(ServletContextEvent event) {
        HiberUtil.closeSessionFactory();
    }
}

This way, the SessionFactory will be created when the web application starts and destroyed when the web application is undeployed/closed.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911