我一直在尝试使用一个小例子来实现休眠。
下面是我的 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="Resource/Person.hbm.xml"/>
并且还尝试将映射 xml 保留在与 hibernate.config.xml 相同的位置。
<mapping
resource="Person.hbm.xml"/>
在上述任何一种情况下,代码都可以找到我的Person.hbm.xml。
我的文件夹结构如下所示
我在 Stackoverflow 上查看了此错误的所有其他答案,但没有一种方法可以解决此问题。非常感谢任何帮助。另外,有什么方法可以进一步调试到粒度级别吗?
请将
hibernate.cfg.xml
放入src
文件夹的根目录中。
并使用
<mapping resource="HibernateExposed/Person.hbm.xml"/>
Hibernate 使用
ClassLoader.getResourceAsStream(resourcePath)
加载所有这些文件 resourcePath
— 是文件的路径
ClassLoader
尝试访问 IDE 中 bin
或 build
文件夹的根目录中的文件,或 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()
它应该位于类路径的根目录中。
这些都不适合我,然后我尝试了这个:-
(替换FactoryConfiguration单例类中的该方法)
private FactoryConfiguration() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(***Class Name***.class);
sessionFactory = configuration.buildSessionFactory();
}
您可以直接给出类名,或者如果它存在于包中,则在映射标记中给出包名和类名并实现它
<mapping class="com.pakagename.Classname"/> ,