1

我正在使用休眠 4 和 Maven:

在此处输入图像描述

所以问题是当我启动服务器时,我看不到它解析 hibernate.cfg.xml 并且表没有在数据库中创建;

休眠.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/mvnodb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping class="tn.onp.mvno.model.Person" ></mapping>
    <mapping class="tn.onp.mvno.model.User" ></mapping>
    <mapping class="tn.onp.mvno.model.Call" ></mapping>
    <mapping class="tn.onp.mvno.model.User" ></mapping>
 </session-factory>

4

1 回答 1

3

根据我们的设置,Hibernate 通常是通过构建 SessionFactory 来启动的。除非您使用某种 Spring / JPA 集成,否则当您启动 tomcat 时,这不会自动发生。

您可以使用以下侦听器在部署和取消部署时初始化和关闭 Hibernate。

public class HibernateListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        HibernateUtil.getSessionFactory(); // Just call the static initializer of that class    
    }

    public void contextDestroyed(ServletContextEvent event) {
        HibernateUtil.getSessionFactory().close(); // Free all resources
    }
}

你需要在你的类路径中包含这个类,以及hibernate jars(+它的dependencies_和你的数据库驱动程序。

您还需要在 web.xml 中配置侦听器

<listener>
    <listener-class>org.mypackage.HibernateListener</listener-class>
</listener>

如果您的 hibernate.cfg.xml 文件有问题,您应该在启动时看到它们。

于 2013-02-08T22:53:52.287 回答