ConfigurationException: 无法在项目根文件夹中找到cfg.xml资源[hibernate.cfg.xml]

17

我有一个hibernate.cfg.xml文件,放在项目根文件夹中。

如果我运行包含以下内容的应用程序:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

configure()方法中崩溃,并显示以下消息:

无法定位cfg.xml资源[hibernate.cfg.xml]

输出

Jun 17, 2016 12:04:59 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
Jun 17, 2016 12:04:59 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.max_fetch_depth=5, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.password=****, hibernate.connection.pool_size=5}
Jun 17, 2016 12:04:59 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:244)
    at o.k.j.HibernateTest.main(HibernateTest.java:22)
10个回答

49
如果你正在使用Maven构建项目,将'hibernate.cfg.xml'文件放置在'src/main/resources'目录下。

1
在花费了大约一个小时的时间进行maven清理、构建、更新等操作后,这个方法对我来说非常有效。 - sss
我该如何配置Maven以在其他地方查找文件? - Amirhosein Al
我有同样的问题,这并没有帮助。 - Sergey Zolotarev
然而,当我之后运行了clean和install(这些是Maven生命周期阶段)时,它成功了。 - Sergey Zolotarev

16

如果您正在使用 Maven 作为构建工具,则将 hibernate.cfg.xml 文件放在 resources 文件夹下。

如何使应用程序引用 Hibernate 配置文件。

右键单击资源文件夹,选择标记目录为选项,然后单击资源根目录

这些步骤适用于我使用的InteliJ IDEA Ultimate 14


16

hibernate.cfg.xml文件应该移动到src文件夹中。


所以我无法为我的hibernate.cfg.xml文件创建一个指定的文件夹! - Menai Ala Eddine - Aladdin

3
hibernate.cfg.xml 文件移动到 src/main/resources 目录下解决了我的问题。

1
如果您正在使用Intellij IDEA,请将文件放置在src/main/resources目录下。

1
以下解决方案可能适用于 Maven、Intellij:
  1. 将 "hibernate.cfg.xml" 移动到资源文件夹 -> 重新构建项目 enter image description here

  2. 右键单击资源文件夹 -> 取消标记资源根目录 -> 再将其标记为资源根目录 enter image description here

    enter image description here


0

使用正斜杠 / 将 cfg 文件放置,如果不使用正斜杠 /,它将无法工作


0

hibernate.cfg.xml

如果您正在使用Eclipse,则必须将其添加到配置中,例如 src \ main \ java \ hibernate.cfg.xml


0
我也遇到了类似的问题,我注意到我的Hibernate配置文件“hibernate.cfg.xml”不在所需的路径上。因此,我将hibernate.cfg.xml移动到src文件夹中,问题得到了解决。

0

它必须作为持久化类型添加到配置文件中。

项目设置 > Facets > 添加Hibernate > 配置路径

然后您可以在视图 > 工具窗口 > 持久性中看到它已配置。

祝好运!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接