Tuesday, August 11, 2009

Using Spring with multiple databases Part 1

This series of articles is about how to use the Spring framework within your application to reference multiple databases or in Java parlance datasources.
In a previous project, I used NHibernate and ActiveRecord and I was able to relatively painlessly use multiple databases. In Spring, to use multiple databases it took longer since my googling came up with some examples , but not complete enough that when tested gave me what I needed. In the Spring framework world and in the Java world in general there all several database persistences technologies. There is plain vanilla Hibernate, there is JPA via Hibernate, there is JPA via TopLink, there is Spring's HibernateTemplating, and plenty more.
To setup Spring with multiple databases, we are going to do the following:
Download and setup SpringFramework 3.0 from the Trunk.
Download and setup Hibernate 3.5 from the Trunk.
Download and setup Atomikos Transaction Manager. (optional download sources)
1) Setup our datasources in our applicationcontext.xml
2) Setup SessionFactory configurations in our applicationcontext.xml
3) Setup JTATransactionManager configurations in our applicationcontext.xml
4) Create a custom JTATransactionFactory class to deal with Hibernate bug: HHH-3110
5) Configure Atomikos (turn off logging on Atomikos)
6) Configure Dao and Controllers with @Transactional annotation
Editors Note: Need @Transactional annotation in Controller , having @Transactional in Dao did not always create a Transaction.
7) Create Unit Tests
8) Take a break!

In part 2, we will setup our datasources. In part 3, we will setup our SessionFactories.