Search code examples
javahibernateamazon-kms

Reading Hibernate configurations dynamically


I need to fetch hibernate connection url, username and password configurations from another service AMS (just like amazon KMS).

I have written another method to fetch those values from AMS. BUT how to set/use these values hibernate to connect my database.

eg. 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){
...
}

how can I achieve this?


Solution

  • Why don't you specify complete configuration in a java file instead of XML?

    See this 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).

    In your case, you can configure somewhat like this in your java file

    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"));