我需要从另一个服务 AMS(就像亚马逊 KMS)获取 hibernate 连接 URL、用户名和密码配置。
我编写了另一种方法来从 AMS 获取这些值。但是如何设置/使用这些值 hibernate 来连接我的数据库。
例如。 hibernate.cfg.xml<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
Util.java
getAMSValue(propertyName){
...
}
我怎样才能实现这个目标?
最佳答案
为什么不在 java 文件中而不是 XML 中指定完整的配置?
<小时/>A org.hibernate.cfg.Configuration also allows you to specify configuration properties.
... ...
This is not the only way to pass configuration properties to Hibernate. Some alternative options include:
- Pass an instance of java.util.Properties to Configuration.setProperties().
- Place a file named hibernate.properties in a root directory of the classpath.
- Set System properties using java -Dproperty=value.
- Include elements in hibernate.cfg.xml (this is discussed later).
就您而言,您可以在 java 文件中进行类似的配置
Configuration configuration = new Configuration().configure();
...
...
configuration.setProperty("hibernate.connection.url", getAMSValue("url"));
configuration.setProperty("hibernate.connection.username", getAMSValue("username"));
configuration.setProperty("hibernate.connection.password", getAMSValue("password"));
关于java - 动态读取 Hibernate 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43132745/