Java 如何从不同位置加载 hibernate.cfg.xml
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20063330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load hibernate.cfg.xml from different location
提问by abhi
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
我正在使用 hibernate 创建一个 jar。我遇到过需要经常更改设置(url)的情况,所以我想加载hibernate.cfg.xml
这样的
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?
如何hibernate.cfg.xml
从与类路径不同的位置加载?
采纳答案by Jayasagar
There is a method public Configuration configure(File configFile)
in class Configuration
有一种方法,public Configuration configure(File configFile)
在课堂上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.
不同之处在于您使用了configure(String resource)
一个在类路径中期望资源的方法,但在configure(File configFile)
期望 a 的地方File
,因此您可以传递它。
回答by sachin10
Hibernate XML configuration file “hibernate.cfg.xml” is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error :
Hibernate XML 配置文件“hibernate.cfg.xml”总是放在项目类路径的根目录下,在任何包之外。如果将此配置文件放到不同的目录中,可能会遇到以下错误:
Initial SessionFactory creation failed.org.hibernate.HibernateException:
/hibernate.cfg.xml not found
To ask Hibernate look for your “hibernate.cfg.xml” file in other directory, you can modify the default Hibernate's SessionFactory class by passing your “hibernate.cfg.xml” file path as an argument into the configure() method:
要让 Hibernate 在其他目录中查找您的“hibernate.cfg.xml”文件,您可以通过将您的“hibernate.cfg.xml”文件路径作为参数传递给 configure() 方法来修改默认的 Hibernate 的 SessionFactory 类:
SessionFactory sessionFactory = new Configuration()
.configure("/com/example/persistence/hibernate.cfg.xml")
.buildSessionFactory();
return sessionFactory;
Full Example in HibernateUtil.java, to load “hibernate.cfg.xml” from directory “/com/example/persistence/“.
HibernateUtil.java 中的完整示例,从目录“/com/example/persistence/”加载“hibernate.cfg.xml”。
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// load from different directory
SessionFactory sessionFactory = new Configuration().configure(
"/com/example/persistence/hibernate.cfg.xml")
.buildSessionFactory();
return sessionFactory;
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
回答by Arthur
supplementing the accepted answer, 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)
补充接受的答案,您可以使用采用 hibernateConfig File 参数的 configure(File configFile) 方法从不同的目录(不一定是类路径)加载 hibernate.cfg.xml。(注意,我使用的是休眠 4.3.7)
The advantage is, if you have no access to the war file but can get access to the hibernate file in a different directory, say for maintenance.
优点是,如果您无权访问 war 文件,但可以访问不同目录中的休眠文件,例如用于维护。
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);
回答by davnicwil
I need to change the sql setting(url) often
我需要经常更改 sql 设置(url)
I had the same requirement. For switching just the DB connection properties the approach suggested in the accepted answer, though it works, is a bit of a blunt instrument.
我有同样的要求。对于仅切换 DB 连接属性,接受的答案中建议的方法虽然有效,但有点生硬。
Loading a completely different configuration file just to change a few connection properties? Now all the other properties that are common in both are duplicated, and every time you make a change you need to make it in two places.
加载一个完全不同的配置文件只是为了改变一些连接属性?现在,两者中共有的所有其他属性都被复制了,并且每次进行更改时都需要在两个地方进行更改。
A better wayis to put all the common properties that don't need to change between environments in the default hibernate.cfg.xml
, build your Configuration
from that as usual, and use the .addProperties()
method to add the properties that are environment-specific on top, in this case the connection url. You can load these extra properties from anywhere you like.
更好的方法是将所有不需要在环境之间更改的公共属性放在 default 中hibernate.cfg.xml
,Configuration
像往常一样从中构建,并使用该.addProperties()
方法将特定于环境的属性添加到顶部,在这种情况下连接网址。你可以从任何你喜欢的地方加载这些额外的属性。
public SessionFactory buildSessionFactory() {
return getConfiguration().buildSessionFactory();
}
private Configuration getConfiguration() {
Configuration config = new Configuration.configure(); // load the base config from the default hibernate.cfg.xml
return config.addProperties(getConnectionProperties()); // add your custom connection props for this environment on top
}
private Properties getConnectionProperties() {
Properties connectionProps = new Properties();
connectionProps.put("hibernate.connection.url", getConnectionUrl());
// possibly add other props like hibernate.connection.username, hibernate.connection.password
return connectionProps;
}
private String getConnectionUrl() {
// get your connection URL from wherever you like
}