【问题标题】:org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not foundorg.hibernate.boot.MappingNotFoundException:未找到映射(资源)
【发布时间】:2016-05-03 14:01:11
【问题描述】:

我一直在尝试使用一个小例子来实现hibernate。

下面是我的hibernate.config.xml

<?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>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/abc
</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<mapping
resource="HibernateExample/src/HibernateExposed/Resource/Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>

运行代码时出现错误 org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found。

我尝试如下替换映射

<mapping
resource="Resource/Person.hbm.xml"/>

并且还尝试将映射 xml 保持在与 hibernate.config.xml 相同的位置。

<mapping
resource="Person.hbm.xml"/>

在以上都没有的情况下,代码可以找到我的Person.hbm.xml。

我的文件夹结构如下所示

我在 Stackoverflow 上查看了此错误的所有其他答案,但没有一种方法可以解决此问题。非常感谢任何帮助。另外,是否有任何方法可以进一步调试到粒度级别?

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    请将hibernate.cfg.xml 放在src 文件夹的根目录下。

    并使用

    <mapping resource="HibernateExposed/Person.hbm.xml"/>
    

    Hibernate 使用 ClassLoader.getResourceAsStream(resourcePath) resourcePath 加载所有这些文件 — 是文件的路径

    ClassLoader 尝试访问 IDE 中 binbuild 文件夹的根目录中的文件,或 jar 的根目录,或用于 Web 应用程序的 war/WEB-INF/classes/ 的根目录。这些都是类路径的根。

    bin 是 Eclipse 编译文件的文件夹。 src文件夹的根目录编译为bin文件夹的根目录。你可以检查一下。

    举个例子

    configure("hibernate.cfg.xml")bin/hibernate.cfg.xml configure("xxx/hibernate.cfg.xml")bin/xxx/hibernate.cfg.xml

     <mapping resource="HibernateExposed/Person.hbm.xml"/>
    

    对应bin/HibernateExposed/Person.hbm.xml

    对于ClassLoader,路径应该没有前导/。 Hibernate 尝试删除前导 /

    这样的路径也是有效的

    <mapping resource="/HibernateExposed/Person.hbm.xml"/>
    

    更新

    你可以指定hibernate.cfg.xml的路径,如果你不想把它放在根目录里

    new Configuration().configure("HibernateExposed/hibernate.cfg.xml")

    如果你使用

    new Configuration().configure()

    它应该在类路径的根目录中。

    【讨论】:

    • 如果我将 hibernate.cfg.xml 放在 src 文件夹中,我会收到错误 org.hibernate.internal.util.config.ConfigurationException: 找不到 cfg.xml 资源。无论如何,hibernate.cfg.xml 应该出现在类路径的根目录中,对吧?在我的例子中,类(Person)是在 HibernateExposed(包)下创建的,所以它的位置应该不是问题。如果我错了,请纠正我。
    • 对 configure(hibernate.cfg.xml) 进行更改后,它起作用了。在过去的 6 个小时里,我一直被这个问题困扰。感谢您的解释!
    • @bestrahul21 我更新了。检查您的构建文件夹。有时 Eclipse 不会清理它。您需要从菜单中选择清洁。
    • @bestrahul21 因为 Eclipse 在您更改文件位置后不会重新构建项目。
    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多