7

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");
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Quak
  • 6,923
  • 4
  • 18
  • 22

4 Answers4

8

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

Adam Sznajder
  • 9,108
  • 4
  • 39
  • 60
  • Thanks, I created classes directory in WEB-INF and it's working fine. – Quak Jan 03 '13 at 16:18
  • 1
    Odd that you had to -create- that directory. You have at least one class that needs to go there! Methinks you are not using Netbeans properly here, but I can only guess. – Gimby Jan 03 '13 at 16:26
  • 2
    @user1946059 It seems like this answer is what you were looking for -- you should accept it. – ach Jan 03 '13 at 16:32
3

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.

Anurag Kapur
  • 675
  • 4
  • 19
1

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);

Arthur
  • 568
  • 7
  • 17
0

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

Krishna
  • 7,154
  • 16
  • 68
  • 80
  • the file does not necessarily need to be in your classpath. see: http://stackoverflow.com/a/27666320/1547266 – Arthur Oct 24 '15 at 16:53