javahibernate

Can not load hibernate.cfg.xml


I was going through a hibernate tutorial and faced this problem. Here is my code

public class HibernateTest {
    public static void main(String[] args) {
        System.out.println(args[0]);
        User user = new User();
        user.setId(1);
        user.setName("John Smith");
        SessionFactory sessionFactory = createSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
    }

    public static SessionFactory createSessionFactory() {
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        return configuration.buildSessionFactory(serviceRegistry);
    }
}

And here is the structure of my project.

enter image description here

But I'm getting an exception, saying

Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found
    at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2095)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2076)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2056)
    at HibernateTest.createSessionFactory(HibernateTest.java:25)
    at HibernateTest.main(HibernateTest.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Solution

  • It's clear in the error that hibernate.cfg.xml file is not in CLASSPATH.

    Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found
    

    To keep the file in CLASSPATH, either move it to the folder /src/main/resources (or) put the current location of the file in CLASSPATH.