一尘不染

如何将属性从外部文件包含到hibernate.cfg.xml?

hibernate

我需要能够在其中存储数据库配置属性,src|main|java|dbConnection.properties并以 jstl*
表达式的hibernate.cfg.xml形式包含它。(例如:$ {password}等)。怎么做?
*

当前的hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
<property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">postgres</property>
        <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    </session-factory>
</hibernate-configuration>

我需要这样的东西:

<?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
    <property name="connection.driver_class">${DRIVER}</property>
            <property name="connection.username">${USERNAME}</property>
            <property name="connection.password">${PASSWORD}</property>
            <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        </session-factory>
    </hibernate-configuration>

阅读 505

收藏
2020-06-20

共1个答案

一尘不染

您声明使用Spring,然后为什么不让Spring进行所有艰苦的工作。让属性占位符替换所需的占位符。

<context:property-placeholder location="classpath:dbConnection.properties" />

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="hibernateProperties">
       <map>
            <entry key="connection.driver_class" value="${DRIVER}" />
            <entry key="connection.username" value="${USERNAME}" />
            <entry key="connection.password" value="${PASSWORD}" />
            <entry key="transaction.factory_class" value="org.hibernate.transaction.JDBCTransactionFactory" />
        </map>
    <property>
 </bean>

免费提供建议,而不使用内部hibernate连接(不建议在生产中使用),在Spring中配置数据源并将其连接到您的 LocalSessionFactoryBean

2020-06-20