我是一个Hibernate的新手,正在尝试使用嵌入式Derby数据库进行小型Hibernate示例。我在Eclipse中开发,没有使用Spring或Maven,也没有设置Web应用程序或应用服务器。如果项目变大,我可能会使用其中一些,但现在我只是想让这个示例正常工作。
我遇到的错误是:
Exception in thread "main" org.hibernate.MappingNotFoundException: resource: javabeat/net/hibernate/EmployeeInfo.hbm.xml not found
有时只需要:
Exception in thread "main" org.hibernate.MappingNotFoundException: resource: EmployeeInfo.hbm.xml not found
这是我的代码;我已经标记出错误似乎来自哪里 - Eclipse控制台显示异常并停止运行,它是逻辑上的地方:
package javabeat.net.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class JavaBeatHibernateExample
{
public static void main(String args[]) throws Exception
{
configureDerbyEmbedded();
Configuration cfg = new Configuration();
cfg.addClass(javabeat.net.hibernate.EmployeeInfo.class);
cfg.setProperty("hibernate.connection.driver_class", "org.apache.derby.jdbc.EmbeddedDriver");
cfg.setProperty("hibernate.connection.password", "password");
cfg.setProperty("hibernate.connection.url", "jdbc:derby:myEmbeddedDB;create=true");
cfg.setProperty("hibernate.connection.username", "admin");
cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
cfg.setProperty("cache.provider_class", "org.hibernate.cache.NoCacheProvider");
// Exception almost certainly generated here.
cfg.addResource("EmployeeInfo.hbm.xml");
cfg.setProperty("hibernate.current_session_context_class", "thread");
cfg.setProperty("hibernate.show_sql", "true");
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
transaction.begin();
EmployeeInfo employeeInfo = new EmployeeInfo();
employeeInfo.setSno(1);
employeeInfo.setName("KamalHasan");
session.save(employeeInfo);
transaction.commit();
session.close();
}
private static void configureDerbyEmbedded()
throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
}
}
我把Eclipse中的文件夹设置如下:
CarRepair
--src
----javabeat
------net
--------hibernate
----main
------resources
--------javabeat
----------net
------------hibernate
我有一个EmployeeInfo.hbm.xml文件,我把它放在以下位置: src/javabeat/net/hibernate main/resources/javabeat/net/hibernate main/resources
但我总是得到上述异常。在第一个位置,它只是说找不到XML文件;在后面两个位置,它在错误消息中在XML文件名之前加上了javabeat/net/hibernate。
该文件应该放在其他地方吗?还是我应该做些其他事情?
编辑:这可能与xml文件本身有关,导致误导性的错误消息吗?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="javabeat.net.hibernate.EmployeeInfo" table="Employee_Info">
<id name="sno" column="sno" type="java.lang.Integer">
</id>
<property name="name" column="name" type="java.lang.String"/>
</class>
</hibernate-mapping>