문제

I tried to run easy test for Hibernate testing but it fails:

public class TestService {
    static {
        PropertyConfigurator.configure("log4j.properties");
    }
    public static void main(String[] args) {
        String mail = "lelyak@gmail.com";
        User user = new UserService().getByEmail(mail);
        System.out.println("user info: " + user.toString());
        System.out.println("\nTHE END");
    }
}

Here is output:

02:24:53,166 ERROR main HibernateUtil:<clinit>:24 - org.hibernate.HibernateException: hibernate.cfg.xml not found
Exception in thread "main" java.lang.NullPointerException
    at com.lelyak.controller.dao.ElementDAOImpl.getAllElements(ElementDAOImpl.java:76)
    at com.lelyak.controller.service.UserService.getListOfObjects(UserService.java:39)
    at com.lelyak.controller.service.UserService.getByEmail(UserService.java:52)
    at com.lelyak.application.TestService.main(TestService.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

HibernateUtil:

public class HibernateUtil {
    private static Logger log = Logger.getLogger(HibernateUtil.class);
    private static SessionFactory sessionFactory = null;
    private static final Configuration configuration = new Configuration();

    static {
        try {
            configuration.configure("hibernate.cfg.xml");
            sessionFactory = configuration.buildSessionFactory(new ServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .buildServiceRegistry());
        } catch (Exception e) {
            log.error(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

cfg file is at project folder:

enter image description here

log4j.properties at the same location is readable. What is wrong with cfg file?

Any suggestion?

도움이 되었습니까?

해결책

You would like to read the file present in folder WebContent,you could try to use likes this

InputStream st= getServletContext().getResourceAsStream("/hibernate.cfg.xml");

But I recommend to put hibernate.cfg.xml under src and your code

 configuration.configure("hibernate.cfg.xml"); 

will be OK.

다른 팁

Hibernate pulls it's hibernate.cfg.xml from the class path rather than the file system. So if you put it in src or src\Java depending on your structure it should work.

You need to put your hibernate.cfg.xml under the src folder and in your code you can do this

 configuration.configure();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top