hibernate - 为什么 Hibernate 找不到/hibernate.cfg.xml?

标签 hibernate postgresql maven classpath hibernate.cfg.xml

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

Initial SessionFactory creation failed.org.hibernate.HibernateException: hibernate.cfg.xml not found

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

这是 session 工厂初始化的代码:

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>

最佳答案

在xml文件前添加正斜杠。

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

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

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

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

关于hibernate - 为什么 Hibernate 找不到/hibernate.cfg.xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31621709/

相关文章:

java - 在构建时获取 Maven 属性

java - hibernate 中的部分架构导出

java - 如何实现Hibernate复合键关系?

postgresql - PostgreSQL-如何将包含秒数的 float 转换为 MM :SS. ss

java - Spring Boot Log4j2 配置日志大小维护问题

java - 覆盖 gradle 中的 Spring Starter Version 版本

java - Hibernate Search、Lucene 或任何其他替代方案?

java - Spring data jpa @Onetomany问题

c++ - 如何在 PostgreSQL 中创建插入、删除或更新命令的信号并在 C++ 中处理它们?

python - "with"语句适用于 Windows 但不适用于 Ubuntu