如何使用hibernate透明地连接到不同的数据库(开发/测试/生产) [英] How to connect to different databases (development/test/production) transparently with hibernate

查看:169
本文介绍了如何使用hibernate透明地连接到不同的数据库(开发/测试/生产)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个不同的数据库为不同的环境连接我的应用程序。这些是每个安装常量,但在它们之间不同。换句话说,有

I have several different databases for different environments to connect my application to. These are constant per installation but differ between them. In other words there is


  1. 连接到开发数据库的开发环境

  2. 测试环境它连接到测试数据库,最后

  3. 具有自己的数据库的生产环境

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

Hibernate is used via Annotations and the code doesn't 'know' which environment it's run in. All the databases are mySQL driven but differ in url, username and password.

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

Currently I removed the hibernate.cfg.xml from the application and moved it to the home directory of the application-server-user but this doesn't seem like a very good solution for security reasons and because this introduced the need to manually update any changed mappings when updating an environment.

我真的希望有一个更好的解决方案,但我找不到一个。

I really hope, there is a better solution but I can't find one.

推荐答案

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

You can bundle the hibernate.cfg.xml in a .jar or you could use a JPA (persistence.xml) approach instead which allows you to have different "persistence units" that you can then choose based on any variable you'd like (a properties file in your home for example). See http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/configuration.html#setup-configuration-packaging for an example of a persistence.xml.

这篇关于如何使用hibernate透明地连接到不同的数据库(开发/测试/生产)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆