views:

4799

answers:

3

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!

+1  A: 

Configuring multiple data sources and session factories in your spring context will not itself be a problem, but it does make autowiring less attractive.

You could use the @Qualifier annotation to tell the autowiring which one to choose, but I'd suggest not using autowiring, and instead explictly injecting the correct data source and session factory using or .

The transaction manager could potentially be shared between both data sources, if both data sources are managed by your app server, but it sounds like having transactional integrity across both data sources is not a requirement for you, and that having seperate transactions for each data source would be enough.

skaffman
+3  A: 

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.

cliff.meyers