Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 623
Quak Avatar asked Jan 03 '13 16:01

Quak


3 Answers

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

like image 99
Adam Sznajder Avatar answered Oct 14 '22 10:10

Adam Sznajder


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.

like image 3
Anurag Kapur Avatar answered Oct 14 '22 10:10

Anurag Kapur


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

like image 1
Arthur Avatar answered Oct 14 '22 11:10

Arthur