1

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

初始 SessionFactory 创建 failed.org.hibernate.HibernateException: hibernate.cfg.xml not found

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>
4

2 回答 2

0

这不是问题的解决方案,但您可以将 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/”。

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

于 2015-09-25T06:50:32.533 回答
0

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

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

您也可以省略参数,因为这是默认参数,例如

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

这是加载类路径上的文件所需的操作。

于 2015-07-25T00:58:31.087 回答