Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load hibernate.cfg.xml from different location

I am creating a jar using hibernate. I have encountered a situation where I need to change a setting (url) often, so I would like to load the hibernate.cfg.xml like this

SessionFactory sessionFactory = new Configuration()
                                     .configure("D:\\fax\\hibernate.cfg.xml")
                                     .buildSessionFactory();

But then running the project I am getting this exception

org.hibernate.HibernateException: D:\fax\hibernate.cfg.xml not found
    at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
    at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1287)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1309)
    at hibernate.LabOrderHelper.getDatabaseSesssion(LabOrderHelper.java:55)
    at hibernate.Test.main(Test.java:42)

How can I load hibernate.cfg.xml from a different location than the class path?

like image 487
abhi Avatar asked Nov 19 '13 04:11

abhi


1 Answers

There is a method public Configuration configure(File configFile) in class Configuration

Try the following, it should work for sure :)

File f = new File("D:\\fax\\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(f).buildSessionFactory();

The difference is you have used a method configure(String resource) which is expecting a resource in a classpath, but where as configure(File configFile) is expecting a File, so you can pass it.

like image 151
Jayasagar Avatar answered Oct 22 '22 09:10

Jayasagar