初始 SessionFactory 创建失败。/resources/hibernate.cfg.xml 未找到

Initial SessionFactory creation failed./resources/hibernate.cfg.xml not found

我使用 Maven Hibernate 创建了简单的项目,但是项目给了我以下错误:

Initial SessionFactory creation failed./resources/hibernate.cfg.xml not     found
org.hibernate.HibernateException: /resources/hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1453)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1475)
at Code.CourseDaoImp.<clinit>(CourseDaoImp.java:16)
at Code.CourseServiceImp.processCourse(CourseServiceImp.java:10)
at Code.app.main(app.java:21)
Exception in thread "main" java.lang.ExceptionInInitializerError
at Code.CourseDaoImp.<clinit>(CourseDaoImp.java:22)
at Code.CourseServiceImp.processCourse(CourseServiceImp.java:10)
at Code.app.main(app.java:21)
Caused by: org.hibernate.HibernateException: /resources/hibernate.cfg.xml not found
at         org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1453)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1475)
at Code.CourseDaoImp.<clinit>(CourseDaoImp.java:16)
... 2 more

resources 是您项目的源文件夹之一。这意味着它包含的所有内容都位于类路径的根部(在默认包中)。所以你需要的代码是

sessionFactory = new Configuration().configure("hibernate.cfg.xml");
  • 将 Java 源移动到 src/main/java
  • *.xml 在 src/main/resources

To meet the standards of MAVEN , like that XML will be added automatically at CLASSPATH