简体   繁体   中英

Spring Boot project can't find Hibernate.cfg.xml when run as executable jar

I see that issues with the hibernate.cfg.xml not being found when SessionFactory is being set up is a somewhat common occurrence, but my question here is somewhat specific. My project works fine when run in Eclipse, even when I move the hibernate.cfg.xml around; I can leave it at the source level and do this:

        Configuration configuration = new Configuration();
        configuration = new Configuration();
        configuration.configure();

Or I can move it to a different location and define it this way:

        Configuration configuration = new Configuration();
        configuration = new Configuration();
        configuration.configure("/path/to/hibernate.cfg.xml");

Both ways work in Eclipse. However, when I build an executable jar to run the application elsewhere, when it launches it complains:

Initial SessionFactory creation 
failed.org.hibernate.internal.util.config.ConfigurationException: Could not 
locate cfg.xml resource [hibernate.cfg.xml]
org.hibernate.internal.util.config.ConfigurationException: Could not locate 
cfg.xml resource [hibernate.cfg.xml]

I understand (or I think I do) that the reason for this is that the hibernate.cfg.xml isn't getting included in the jar itself and so even when the path is defined it can't find it but am not sure how to fix it. I think if I can get the file into the jar then it may work (maybe the classpath also needs an entry for this?) but I'm actually not sure how to do so.

It mainly depends on whether you are using a framework or not and if yes the which framework you are using. If you are not using any framework then keeping hibernate.cfg.xml file in your root path can be fine. But Because of urge in standardising the coding process, frameworks usually expect the file in your resources folder.But in your case you should give the path to that configuration file not relative to the root folder but entire path.

I think you are using absolute path here:

configuration.configure("/path/to/hibernate.cfg.xml");

Instead of that you should use classpath loader. Something like this :

Resource r = new ClassPathResource("hibernate.cfg.xml")
String path = r.getURI().getPath();
configuration.configure(path);

This should work after packaging jar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM