配置 Hibernate 使用数据库,其名称在运行时未知
我有一个在 Java 6、Spring 2.5.6 和 Hibernate 3.2.7 上运行的 Web 应用程序。现在需要从多个数据库中获取一些数据,这些数据的名称在运行时之前是未知的。实现这一目标的最佳方法是什么?
我查看了例如 http://blog.springsource 的文章。 com/2007/01/23/dynamic-datasource-routing/,但这似乎只适用于预先知道所有数据库配置的情况。
I have a web application running on Java 6, Spring 2.5.6 and Hibernate 3.2.7. Now there is a requirement to fetch some data from several databases, whose names are not known before the runtime. What is the best way to achieve this?
I have looked e.g. into the article at http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/, but that seems to be applicable only in a situation, where all the database configurations are known beforehand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在Java代码中进行配置,因此可以在运行时进行配置:
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/session-configuration.html#configuration-programmatic
You can do configuration in Java code, so you can do it at runtime:
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/session-configuration.html#configuration-programmatic
您可以创建一个实现 org.hibernate.connection.ConnectionProvider 的类。然后在您的休眠配置文件中添加该类,如下所示:
您可能也希望每个数据库都有一个不同的 sessionFactory 。您能否提供有关您的应用程序如何在运行时查找数据库连接的更多信息?
You could create a class that implements
org.hibernate.connection.ConnectionProvider
. Then in your hibernate configuration file add that class like this:You probably want a different sessionFactory for each database too. Can you provide any more information about how your app finds out about the database connections at runtime?
由于每个数据库的数据库结构都是相同的(尽管它们的名称事先未知),我决定简单地通过将数据库名称作为参数添加到查询中来实现它。这避免了使用多个会话工厂带来的资源和管理问题。
更多信息请参见:http://web.archive。 org/web/20071011173719/http://hibernate.org/429.html
As the database structure is same for each database (although their names are not known beforehand), I decided to impement it simply by adding the database name to the query as parameter. This avoids the resource and management problems from using multiple session factories.
More information from here: http://web.archive.org/web/20071011173719/http://hibernate.org/429.html