Java – Hibernate + Spring using multiple datasources

hibernatejavaspringspring-mvc

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!

Best Answer

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.

Related Topic