如何使用 Tomcat 8 或 9 在部署时自动启动 Hibernate

How to auto start Hibernate at deploy-time with Tomcat 8 or 9

我有 HibernateUtil class 和实体包、servlet 和 jsp。在 Tomcat 上部署我的 war 文件后,我应该在我的代码或休眠配置文件中添加什么以开始创建所有 H2 表(根据我的实体),在第一次调用之前(在我的情况下这是登录)

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

}

虽然最好使用 Java EE 或 Spring 等自动管理资源的容器,但您仍然可以手动进行。

您需要在web.xml中添加监听器:

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

然后实现监听如下:

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

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

这样,SessionFactory 将在 Web 应用程序启动时创建,并在 Web 应用程序 undeployed/closed 时销毁。