I am new to Hibernate, reading this book \"Java persistence with Hibernate\" and I am trying to implement the example from there. So far my Ant build is successful, but when
It shouldn't be in your root directory, it should be on your classpath.
Your hibernate.cfg.xml
needs to be inside the src
directory; otherwise it's not covered by Ant's copymetafiles
target, so it won't end up in your compiled classpath.
The hibernate.cfg.xml file shoul be in root directory of the classpath of your project. If you using Maven then make sure it should be like src > resources > hibernate.cfg.xml.
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, I am using hibernate 4.3.7)
Like this:
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);
If you are working on Intellij Idea
then make a folder named "resources" under src\main\java. Open Module setting of your project, select "Modules" from left and in the "sources" tab select the newly created "resources" folder and mark it as "Resources". Create thehibernate.cfg.xml
file inside this newly created "resources" folder.
then this should work
Configuration con = new Configuration().configure("hibernate.cfg.xml");
Though it it is late, The solution is you need to put this configuration file inside resource folder(projectxxxx->Resources) provided its a maven project.