如何从不同位置加载hibernate.cfg.xml [英] How to load hibernate.cfg.xml from different location
问题描述
我正在使用hibernate创建一个jar。我遇到过需要经常更改设置(url)的情况,所以我想像这样加载 hibernate.cfg.xml
SessionFactory sessionFactory = new Configuration()
.configure(D:\\fax\\hibernate.cfg.xml )
.buildSessionFactory();
但是运行项目后,我得到这个异常
org.hibernate.HibernateException:D:\ fax \hibernate.cfg.xml未找到
,位于org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper。
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1287)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1309)
在hibernate.LabOrderHelper.getDatabaseSesssion(LabOrderHelper.java:55)
at hibernate.Test.main(Test.java:42)
如何从不同于类路径的位置加载 hibernate.cfg.xml
?
public Configuration configure(File configFile)
code> 请尝试以下操作,它应该可以确保:)
文件f =新文件(D:\ \\fax\\hibernate.cfg.xml);
SessionFactory sessionFactory = new Configuration()。configure(f).buildSessionFactory();
不同之处在于您使用了一个方法 configure(String resource) code>期望类路径中的资源,但是
所期望的是 File $ c $> c>,所以你可以传递它。
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?
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.
这篇关于如何从不同位置加载hibernate.cfg.xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!