如何使用hibernate透明地连接到不同的数据库(开发/测试/生产)



我的应用程序要连接到不同环境的几个不同数据库。这些在每次安装中都是恒定的,但它们之间有所不同。换句话说,有

    连接到开发数据库的开发环境
  1. 连接到测试数据库的测试环境,最终
  2. 带有自己数据库的生产环境

Hibernate是通过注解使用的,代码不知道它在哪个环境中运行。所有的数据库都是mySQL驱动的,但不同的url,用户名和密码。

目前,我从应用程序中删除了hibernate.cfg.xml,并将其移动到application-server-user的主目录中,但出于安全原因,这似乎不是一个很好的解决方案,因为这引入了在更新环境时需要手动更新任何更改的映射。

我真的希望有更好的解决办法,但是我找不到。

您可以将hibernate.cfg.xml捆绑在.jar中,或者您可以使用JPA (persistence.xml)方法,它允许您拥有不同的"持久性单元",然后您可以根据您喜欢的任何变量(例如,您家中的属性文件)进行选择。有关persistence.xml的示例,请参阅http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/configuration.html#setup-configuration-packaging。

为配置文件中的url、用户和密码使用占位符,并在构建应用程序时(使用ant、Maven或任何您用来构建应用程序的东西)将这些占位符替换为实际值。构建过程本身可以从概要文件(如果使用Maven)、环境变量或命令行参数中获取这些值。

您只需要用不同的参数构建应用程序三次:每个目标环境一次。

我认为这里的重点是不要重新构建应用程序3次。我认为您可以使用不同的数据源,将在不同的环境(开发/测试/prod)中定义您的数据库服务器的不同url。数据源文件是一个xml文件,应该驻留在工件的外部(ear/war或您构建的任何文件)。

为不同的环境提供相同的ear和不同的数据源文件

我是这样做的。我的应用配置文件

 <!-- Hibernate MySql SessionFactory -->
 <bean id="mySqlSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
      p:dataSource-ref="mySqlDataSource">
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
   .....
        </props>
    </property>
    <property name="configLocation" value="WEB-INF/hibernate.cfg.xml"/>
</bean>

然后我有这些变量定义在不同的属性文件即etc/dev/pejl。属性等/测试/ pejl。pejl.properties和etc/prod/

然后使用我的ant脚本构建开发…

<target name="deploydevwar" depends="build" description="Deploy application as a WAR file">
     <copy overwrite="true" todir="${web.dir}/WEB-INF/classes">
        <fileset dir="${etc.dir}/dev">
            <include name="*.properties" />               
        </fileset>
        </copy>
    <war destfile="${name}.war"
         webxml="${web.dir}/WEB-INF/web.xml">
        ...
   </war>
    <copy todir="${deploy.path}" preservelastmodified="true">
       .. 
    </copy>
     <copy overwrite="true" todir="${appserver.home}">
         ...
     </copy>            
</target>
为测试. .

<target name="deploytestwar" depends="build" description="Deploy application as a WAR file">
     <copy overwrite="true" todir="${web.dir}/WEB-INF/classes">
        <fileset dir="${etc.dir}/test">
            <include name="*.properties" />               
        </fileset>

等等…

最新更新