Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap out hibernate.cfg.xml properties?

I've got a Hibernate configuration file hibernate.cfg.xml where are hard-coded property names like:

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">mysecretpassword</property>
    ...
  </session-factory>
</hibernate-configuration>

I want to swap out things like the username and the password to a .properties-file. So that I will get the following:

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.username">${jdbc.username}</property>
    <property name="hibernate.connection.password">${jdbc.password}</property>
    ...
  </session-factory>
</hibernate-configuration>

How can I do that? For the dataSource in Spring I can use this one in my applicationContext.xml:

<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="/WEB-INF/jdbc.properties" />

What is the equivalent for Hibernate?

like image 726
Benny Neugebauer Avatar asked Sep 25 '10 19:09

Benny Neugebauer


1 Answers

Remove config parameters from hibernate.cfg.xml and declare the following:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=${hibernate.dialect}
        </value>
    </property>
</bean>
like image 145
Val Avatar answered Sep 28 '22 05:09

Val