gpt4 book ai didi

java - 动态读取 Hibernate 配置

转载 作者:行者123 更新时间:2023-11-30 06:49:13 25 4
gpt4 key购买 nike

我需要从另一个服务 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 中指定完整的配置?

查看此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"));

关于java - 动态读取 Hibernate 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43132745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com