Question

I am writing a web application and I have to add hibernate. I configured maven (pom.xml) etc. but now I am getting the following error:

exception
javax.servlet.ServletException: org.hibernate.HibernateException: /hibernate.cfg.xml not found

I am using NetBeans. I tried moving this file to WEB-INF, root project folder, src directory (default package) but it's still not working. How can I do? I don't want to set path to this file programmatically like this:

Configuration cfg = new Configuration();
cfg.addResource("/some/path/to/this/file/Hibernate.cfg.xml");
Was it helpful?

Solution

I always put it into WEB-INF/classes directory (compiled files are stored there).

OTHER TIPS

You need to add the hibernate.cfg.xml to a folder in the classpath. In a webb app, WEB-INF/classes is in the classpath by default. You can either use that folder or create a new one for your resources (assuming you want to keep them separate) and then set the new folder in classpath by adjusting your project settings.

You can load hibernate.cfg.xml from a different directory (not necessarily the classpath) using the configure(File configFile) method that takes the hibernateConfig File argument. (note, am using hibernate 4.3.7)

The advantage is, you can place your hibernate configs file in a separate directory which you are bound to have access to (for maintenance or change purposes) other than bundling it together with the .war file which you may not have access to.

Example follows:


String hibernatePropsFilePath = "/etc/configs/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);

Configuration configuration = new Configuration(); 
configuration.configure(hibernatePropsFile);

StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

This file must be in the root of classpath of the application. That is under WEB-INF/classes

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top