动态读取 Hibernate 配置

Reading Hibernate configurations dynamically

我需要从另一个服务 AMS(就像 amazon KMS)获取休眠连接 url、用户名和密码配置。

我已经编写了另一种方法来从 AMS 获取这些值。但是如何 set/use 这些值休眠以连接我的数据库。

例如。 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 中指定完整配置?

看到这个documentation

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:

  1. Pass an instance of java.util.Properties to Configuration.setProperties().
  2. Place a file named hibernate.properties in a root directory of the classpath.
  3. Set System properties using java -Dproperty=value.
  4. 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"));