【问题标题】:Why can't Hibernate find /hibernate.cfg.xml?为什么 Hibernate 找不到 /hibernate.cfg.xml?
【发布时间】:2015-10-15 18:52:04
【问题描述】:

我正在尝试学习 Hibernate + Maven。我正在尝试连接到 PostgreSQL 数据库,但出现以下错误:

初始 SessionFactory 创建失败.org.hibernate.HibernateException: hibernate.cfg.xml 未找到

hibernate.cfg.xml 文件已经在src/main/resources 文件夹下,我已经将该文件夹添加为源文件夹。

这里是会话工厂初始化的代码:

Configuration  configuration = new Configuration().configure("hibernate.cfg.xml");
        return  configuration.buildSessionFactory();

编辑:这里是 pom.xml

    <modelVersion>4.0.0</modelVersion>

  <groupId>com.jee.mavenapp</groupId>
  <artifactId>hibernate-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>hibernate-example</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.12</version>
    </dependency>
  </dependencies>

【问题讨论】:

    标签: hibernate postgresql maven classpath hibernate.cfg.xml


    【解决方案1】:

    在 xml 文件前面添加一个正斜杠。

    Configuration  configuration = new Configuration().configure("/hibernate.cfg.xml");
    

    你也可以省略参数,因为那是default parameter,例如

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

    这是您加载 classpath 上的文件所需执行的操作。

    【讨论】:

    • 感谢您的回复。我已经测试了这些选项,但仍然遇到同样的错误。还有其他建议吗?
    • @TuncerTunçer /src/main/resources 应该是资源文件夹而不是源文件夹。可以包含相关的 pom sn-ps 吗?
    【解决方案2】:

    这不是解决问题的方法,但是您能否将 hibernate.cfg.xml 文件与构建会话工厂的 Java 类放在同一个包中(以确保它在您的类路径中)。并做这样的事情

    Configuration  configuration = new Configuration().configure("/com/github/fluent/hibernate/example/mysql/hibernate.cfg.xml");
    return  configuration.buildSessionFactory();
    

    用你的类的包替换“/com/github/fluent/hibernate/example/mysql/”。

    附:你可以在这里找到一个非常简单的控制台 Hibernate 应用程序 fluent-hibernate-mysql

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-11
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      相关资源
      最近更新 更多