使用多个数据源的Hibernate + Spring? [英] Hibernate + Spring using multiple datasources?

查看:123
本文介绍了使用多个数据源的Hibernate + Spring?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用Spring MVC 2.5和Hibernate的Web应用程序。



应用程序的一个要求是它必须能够导出一些对象到外部数据库。我想我可能会使用我现有的数据层,并将对象保存到外部源。



我是Spring和Hibernate的新手,我想我'我只是想知道我应该如何解决这个问题。现在一切都通过注释自动连接起来。我猜我必须创建一个新的dataSource bean,一个新的sessionFactory和一个transactionManager ......也许......但是......


  1. 我只想连接到外部数据源,当用户明确地导出时。

  2. 自动装配会妨碍我?当我为我的导出过程实例化DAO时,如何告诉Spring注入适当的sessionFactory? (我通过构造函数自动装配)我应该编程创建我的会话工厂(等),然后手动实例化我的DAO?如果是这样,这会覆盖自动装配注释吗?


    我想我不需要上述答案特别是如果有人能够引导我完成像这样的工作的基本过程。谢谢!

    解决方案

    幸运的是,Spring已经有了一个解决方案:AbstractRoutingDataSource。它基本上充当多个DataSource的Facade,并允许您对其进行子类化并实现您需要决定使用哪个DataSource的任何逻辑。一些细节在这里:

    http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/



    这允许您的DataSource查找逻辑要在一个地方处理。除了需要将AbstractRoutingDataSource的子类注入到Hibernate SessionFactory中之外,您的DAO层和SessionFactory无需调整。


    I'm working on a web application that uses Spring MVC 2.5 and Hibernate.

    One of the requirements of the application is that it must be able to export some objects to an external database. I figure I might as well use my existing data layer and just save the objects to the external source.

    I'm new to Spring and Hibernate, and I guess I'm just wondering how I should approach this. Right now everything is automatically wired up through annotations. I'm guessing I'll have to create a new dataSource bean, and a new sessionFactory, and a transactionManager...maybe...but...

    1. I only want the connection to the external data source to be available when the user is specifically "exporting".

    2. Is autowiring going to get in my way? How can I tell Spring to inject the appropriate sessionFactory when I instantiate a DAO for my export process? (I'm autowiring through constructors) Should I programatically create my session factory (etc) and then manually instantiate my DAO? If so, will this "override" the autowire annotation?

    I guess I don't need answers to the above questions specifically if someone can just step me through the basic process of getting something like this to work. Thanks!

    解决方案

    Spring fortunately already has a solution for this: AbstractRoutingDataSource. It basically acts as a Facade for multiple DataSources and allows you to subclass it and implement whatever logic you need to decide which DataSource should be used. Some details are here:

    http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/

    This allows your DataSource lookup logic to be handled in exactly one place. Your DAO layer and SessionFactory do not need to be adjusted, except that you need to inject your subclass of AbstractRoutingDataSource into the Hibernate SessionFactory.

    这篇关于使用多个数据源的Hibernate + Spring?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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