org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/HibernateTest/src/hibernate.cfg.xml]

我们两清 提交于 2019-11-30 04:03:51

If you have your hibernate.cfg.xml in the root of the source folder, just do

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

If it is in the package, for an example in the org.nitish.caller, specify path by this way

 SessionFactory sessionFactory = new Configuration()
    .configure("/org/nitish/caller/hibernate.cfg.xml").buildSessionFactory();

You need to close the session (in the finally block). Don't forget to add rollback code.

Please, add @Table annotation to the UserDetails.

Update

The reason of the error that Hibernate can't find org.postgresql.Driver class. It resides in postgresql jar. You have that jar at your image, but may be you don't add it to the classpath. Refer How to Add JARs to Project Build Paths in Eclipse (Java).

To close a session in the finally block you need to have session variable outside the try block.

    Session session = sessionFactory.openSession();

    try{

    } finally {
        session.close();
   }

new Configuration().configure() takes hibernate.cfg.xml from root of class path directory. new Configuration().configure("/com/company/project/hibernate.cfg.xml") takes from root of class path + com/company/project/hibernate.cfg.xml.

If you are using different file name for hibernate configuration from root of class path, then eg: new Configuration().configure("/database.cfg.xml")

If you want to give the full system path of the configuration file then new Configuration().configure(new File("/home/visruth/config/hibernate.cfg.xml)) which takes the configuration file from the given exact location.

ASH

I fixed this by moving my config file to src/main/resources. This is the standard directory for configuration files like hibernate.cfg.xml or hibernate.properties or application related properties files.

Parth Mehta

All the previous answers are perfect. However, if u need a really quick solution then I would recommend you to just put your hibernate.cfg.xml file in your source folder and write

SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

This is simple and works!

new Configuration().configure(new File("hibernate.cfg.xml")).buildSessionFactory());

This solved the error for me!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!