Quak
Quak

Reputation: 7443

web application - where to place hibernate.cfg.xml file?

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

Upvotes: 7

Views: 19215

Answers (4)

Arthur
Arthur

Reputation: 608

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

Upvotes: 1

Krishna
Krishna

Reputation: 7294

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

Upvotes: 0

Anurag Kapur
Anurag Kapur

Reputation: 675

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.

Upvotes: 3

Adam Sznajder
Adam Sznajder

Reputation: 9206

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

Upvotes: 8

Related Questions