【问题标题】:org.hibernate.HibernateException: /hibernate.cfg.xml not foundorg.hibernate.HibernateException:/hibernate.cfg.xml 未找到
【发布时间】:2011-06-23 11:44:51
【问题描述】:

我正在尝试将休眠与 spring 3 mvc 一起使用,但目前我抛出了这个异常。我想我需要在某个地方定义我的hibernate.cfg.xml,但不确定在哪里?

我基本上在这里遵循了这个例子http://www.nabeelalimemon.com/blog/2010/05/spring-3-integrated-with-hibernate-part-a/ 并且特别看到了这行代码,假设使用这个“神奇地”找到我的 hibernate.cfg 文件:

return new Configuration().configure().buildSessionFactory();

我猜这不正确?我目前在 src/com/jr/hibernate/ 中有我的 hibernate.cfg 文件

下面是我的cfg文件:

<?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>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/racingleague</property>
    <property name="connection.username">username</property>
    <property name="connection.password">password</property>
    <property name="hibernate.format_sql">true</property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>
    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <!-- Echo all executed SQL to stdout -->
    <property name="hibernate.show_sql">true</property>
    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">update</property>
    <!--property name="hbm2ddl.auto">update</property-->
    <mapping resource="com/jr/model/hibernateMappings/user.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

我的休眠实用程序类:

package com.jr.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

     private static final SessionFactory sessionFactory = buildSessionFactory();

      public static SessionFactory buildSessionFactory() {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
          return new Configuration().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);
        }
      }

}

这个抽象类被称为:

package com.jr.db;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import com.jr.utils.HibernateUtils;

public abstract class DbWrapper<T> {

    private static SessionFactory sessionFactory = null;
    private static Session session;

    public DbWrapper() {
        setSessionFactory();
    }

    private void setSessionFactory() {
        sessionFactory = HibernateUtils.buildSessionFactory();
        session = sessionFactory.getCurrentSession();
    }

    public boolean addNewItem(T dbItem) {

        try {
            session.getTransaction().begin();
            session.save(dbItem);
            session.getTransaction().commit();
        } catch (Exception e) {
            System.err.println("error exception when adding new item to table"
                    + e);
        } finally {

            session.close();
            sessionFactory.close();
        }

        return false;

    }

    public abstract boolean removeItem(String uid);

    public abstract boolean modifyItem(String uid, T item);

}

这是最初执行一些休眠操作的控制器:

private Logger logger = Logger.getLogger(UserController.class);

    private UserDb userDb;

@RequestMapping(value = "/user/registerSuccess", method = RequestMethod.POST)
public String submitRegisterForm(@Valid User user, BindingResult result) {

    // validate the data recieved from user
    logger.info("validate the data recieved from user");
    if (result.hasErrors()) {
        logger.info("form has "+result.getErrorCount()+" errors");

        return "account/createForm";
    } else{
        // if everthings ok, add user details to database
        logger.info("if everthings ok, add user details to database");

        userDb = new UserDb();

        userDb.addNewItem(user);

        // display success and auto log the user to the system.
        return "account/main";
    }

}

提前干杯。我的所有表 hibvernate xml 映射也与我的 hibernate.cfg.xml 文件位于同一位置

【问题讨论】:

    标签: java hibernate spring-mvc


    【解决方案1】:

    hibernate.cfg.xml 必须在 webapp 启动时在类路径的根目录中找到。

    如果你使用maven构建项目,请将hibernate.cfg.xml放到src/main/resources目录下,这样构建war包的时候会自动放到/WEB-INF/classes

    如果不使用 maven,请将文件直接放在您的 WEB-INF/classes 目录中。

    【讨论】:

      【解决方案2】:

      hibernate.cfg.xml 应该在WEB-INF/classes 中。或者,您可以通过将相应的参数传递给 configure(..) 方法从自定义位置加载它。

      【讨论】:

      • 博卓,config.configure("/resources/hibernate.cfg.xml"); 不适合我。实际上,我正在做一个简单的hibernate 3.1 应用程序。顺便说一句,config 的类型为 AnnotationConfiguration
      【解决方案3】:

      不要将hibernate.cfg.xml文件放在src/com/jr/hibernate/目录下,而是将它放在src目录下。然后它会自动出现在WEB-INF/classes 目录中,正如这里的人们所提到的。

      【讨论】:

      • 干杯。有用。我有另一个问题。我的应用程序似乎无法找到我的休眠 xml 映射。我将它放在 com.jr.hibernateMappings 中,但 build.xml 似乎没有构建和编译我的 hbm.xml 文件。是不是又放错位置了?它是否需要在 WAR/WEB-INF/classes 文件夹中?如果可能的话,我更希望它在 src 目录中
      • 谢谢...在将我的文件(hibernate.cfg.xml)移动到 src 后,它会再次找到该文件
      【解决方案4】:

      在 IntelliJ 中,转到“打开项目设置”>> 模块>> Hibernate 并定位项目中使用的 hibernate.cfg.xml 文件。

      【讨论】:

        【解决方案5】:

        我也有同样的问题,把hibernate.cfg.xml移到src/main/resources目录解决了,会自动放到/WEB-INF/classes下。

        【讨论】:

          【解决方案6】:

          如果您使用 Maven,您应该将文件 hibernate.cfg.xml 放在 Intellij IDEA 中的以下路径 /src/main/java/resources/hibernate.cfg.xml 中。然后,在您运行的应用程序类中插入行:

          SessionFactory 工厂 = 新 Configuration().configure("hibernate.cfg.xml").addAnnotatedClass().buildSessionFactory();

          【讨论】:

          • 谢谢。在这之后我几乎浪费了 2 天。
          • 那么 NetBeans 呢?
          【解决方案7】:

          即使我在src 文件夹下有hibernate.cfg.xml,我也会得到

           org.hibernate.HibernateException: /hibernate.cfg.xml not found
          

          在运行mvn clean install 之后。通过尝试和错误,我能够通过从折叠的src 中删除 hibernate.cfg.xml 并添加到其他地方来解决它。运行应用程序(在我的例子中它是一个主类)。在此期间,我仍然收到错误消息。并将其添加回src 文件夹并朗姆酒主类。 It worked!

          【讨论】:

            猜你喜欢
            • 2016-12-02
            • 1970-01-01
            • 2012-01-02
            • 2015-02-07
            • 1970-01-01
            • 2014-03-12
            • 2013-01-24
            • 1970-01-01
            相关资源
            最近更新 更多