简体   繁体   English

hibernate.cfg.xml-从属性文件设置参数

[英]hibernate.cfg.xml - Set parameters from a properties file

I've this file hibernate.cfg.xml that I use to configure hibernate at sturtup. 我有这个文件hibernate.cfg.xml ,用于在sturtup上配置hibernate。

<property name="hibernate.connection.username">dbUser</property>
<property name="hibernate.connection.password">1234</property>

I've a properties file that it's called config.properties that hold all other configurations used into the application. 我有一个名为config.properties的属性文件,其中包含应用程序中使用的所有其他配置。

How can I set "hibernate.connection.username" parameter from the properties file (config.properties) so I have only one file to edit? 如何从属性文件(config.properties)设置“ hibernate.connection.username”参数,这样我只能编辑一个文件?

It depends on the destination of the properties stored in config.properties 这取决于config.properties中存储的属性的目标

If they go in the java System properties, you can use them in your hibernate config like this : 如果它们进入java System属性,则可以在休眠配置中使用它们,如下所示:

<property name="hibernate.connection.password">${propertyName}</property>

If your properties go somewhere else, then I don't think hibernate will see them naturally... 如果您的物业不在其他地方,那么我认为休眠不会自然地看到它们……

对我来说,解决方案是在运行时将属性添加到配置中:

configuration.setProperty("hibernate.connection.username", Config.db.getUser());

I do it like that: 我这样做:

Map<String, Object> prop = new HashMap<String, Object>();

prop.put("hibernate.connection.username", "asdf");
prop.put("hibernate.connection.password", "xxx");


Persistence.createEntityManagerFactory(persistenceUnitName, prop);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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