Hibernate:映射未找到exception
从官方文档开始Hibernate。 我陷入了配置xml文件的最基本步骤。 虽然我已按照示例中的描述完成了所有操作,但无法找到The mapping file
。
这是例外:
Exception in thread "main" org.hibernate.MappingNotFoundException: resource: testing/ground/beans/User.hbm.xml not found at org.hibernate.cfg.Configuration.addResource(Configuration.java:728) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2115) at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2087) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2067) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2020) at org.hibernate.cfg.Configuration.configure(Configuration.java:1935) at org.hibernate.cfg.Configuration.configure(Configuration.java:1914) at testing.ground.test.HibernateTest.main(HibernateTest.java:14)
使用main()的代码:
package testing.ground.test; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateTest { private SessionFactory sessionFactory; public static void main(String[] args) { HibernateTest ht = new HibernateTest(); ht.sessionFactory = new Configuration().configure().buildSessionFactory(); ht.getData(); } public void getData(){ Session session = this.sessionFactory.getCurrentSession(); session.beginTransaction(); List list = session.createQuery("from users").list(); System.out.println(list); session.getTransaction().commit(); session.close(); } }
Hibernate配置文件:
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/somedb?characterEncoding=UTF-8 username 1 org.hibernate.dialect.MySQLDialect true
我试图保持文件夹结构与Hiberante示例中的相同:
请指教。
将user.hbm.xml文件放在testing.ground.beans包下的资源文件夹中
看起来你正在使用Maven来构建你的项目。 Maven期望资源(即非Java文件)位于src/main/resources
。 不是undr src/main/java
。
也就是说,找到另一个教程如何使用注释来映射实体。 XML映射已过时,并且比注释更难使用。 作为额外的奖励,您还将学习如何使用EclipseLink和所有其他JPA引擎,因为注释是标准的,而XML映射则不是。
将User.hbm.xml
移动到src/main/resources
正确包( testing.ground.beans
)。 我想你的构建工具不会从src/main/java
选择资源
你也可以使用