代码之家  ›  专栏  ›  技术社区  ›  Benny Code

如何交换hibernate.cfg.xml属性?

  •  7
  • Benny Code  · 技术社区  · 14 年前

    我有一个 冬眠 配置文件 hibernate.cfg.xml 硬编码的属性名在哪里,如:

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

    我想交换用户名和密码到 .properties -文件。因此,我将得到以下信息:

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

    我怎么能做到呢?对于 春季数据源 我可以在我的 applicationContext.xml

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

    什么是Hibernate的等价物?

    3 回复  |  直到 10 年前
        1
  •  4
  •   Val    12 年前

    从中删除配置参数hibernate.cfg.xml并声明如下:

    <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>
    
        2
  •  3
  •   Pascal Thivent    14 年前

    hibernate.cfg.xml 并在 hibernate.properties 放在类路径上的文件。但是您确实需要从XML配置文件中删除它们,因为它会覆盖“遗留”属性文件中的属性。文件来源:

    3.7. XML configuration file

    另一种方法 配置是指定一个完整的 名为的文件中的配置 hibernate.cfg.xml . 这个文件可以是 用作 属性文件 文件或,如果两者都是

    如果这不是一个选项(如果您不能在Spring配置文件中配置Hibernate),那么您必须在构建时使用构建工具(Ant、Maven等)中的一些过滤特性来处理这个问题。

        3
  •  0
  •   rogerdpack    13 年前

    配置对象有一个readProperties方法(但我不知道您描述了什么)。如果您计划使用自定义属性或重写休眠.cfg.xlm,请确保先调用configure(),然后调用setProperty或setProperties。