hibernate: Duplicate class/entity; Could not parse mapping document from resource

近日在学习Hibernate时,总是遇到以下异常:

org.hibernate.InvalidMappingException: Could not parse mapping document from resource kpy/db/Customer.hbm.xml
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3415)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3404)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3392)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1341)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1737)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1788)
    at kpy.db.CustomerDao.<clinit>(CustomerDao.java:24)
    at kpy.HibernateDemo.App.main(App.java:15)
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mappingkpy.db.Customer
    at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2580)
    at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:174)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3412)
    ... 7 more


测试代码如下:

	private static SessionFactory sessionFactory;
	
	static {
		try{
			Configuration config = new Configuration();
			LogWriter.info("new Configuration success.");
			
			// 以下这一句不能少,少了报异常:hibernate Connection cannot be null when 'hibernate.dialect' not set
			config.configure("/kpy/db/hibernate.cfg.xml");
			
			config.addClass(Customer.class);
			LogWriter.info("add Customer.class success.");
			
			sessionFactory = config.buildSessionFactory();
			
			LogWriter.info("build buildSessionFactory success.");
			
		}catch (Exception e){
			e.printStackTrace();
		}
	}

查找了大量资料,总是找解决问题:原因在于代码中,红色的两句。

在文件/kpy/db/hibernate.cfg.xml中,已经包含了以下这一句:

<mapping resource="kpy/db/Customer.hbm.xml"/>

而在文件中kpy/db/Customer.hbm.xml有如下定义。

<class name="kpy.db.Customer" table="CUSTOMERS">

进行config.configure("/kpy/db/hibernate.cfg.xml");操作时,对XML文件进行解析。根据<class name="kpy.db.Customer" table="CUSTOMERS">已经知道了需要对kpy.db.Customer做映射,因此不再需要config.addClass(Customer.class);  


在《精通 Hibernate:Java 对象持久化技术详解(第2版)》一书4.5小节中,有如下描述:

如果Hibernate的配置文件为XML格式,只需要在配置文件中声明映射文件,在程序中不必调用Configuration类的AddClass()方法来加载映射文件。当映射文件名发生变化,只需要修改XML格式的配置文件,不需要修改程序代码,因此XML格式的配置文件会提高应用程序的可维护性。




猜你喜欢

转载自blog.csdn.net/lijing_lj928/article/details/50629713
今日推荐