Spring Roo: Two Databases Configuration
- By Jose Delgado on January 27, 2011
I’ve seen very often a recurrent question on Spring Roo forums. The question is “How to configure the application to handle two databases”.
Certainly this is a more ample question to Spring Roo only, due it involves JPA and the Spring persistence stack. So, I believe it will be of interest to all the Spring development community that face such problem.
I am assuming the Reader is a Java Developer with some familarity with Spring Roo. I focus on to how to get to configuration only. For help on how to use Roo, please visit http://www.springsource.org/roo.
Hands on the problem
I created the following minimal Roo project (shown below) for explaining the setup. I’ll modify the configuration in a way that each entity will come from different independent databases.
project --topLevelPackage org.pragmatikroo.twodb persistence setup --provider HIBERNATE --database MYSQL --userName
--password --databaseName twodbone logging setup --level DEBUG --package PERSISTENCE entity --class ~.domain.DbOne field string --fieldName name entity --class ~.domain.DbTwo field string --fieldName name perform clean perform eclipse exit
Database.properties file original
database.url=jdbc\:mysql\://localhost\:3306/twodb database.username= database.driverClassName=com.mysql.jdbc.Driver
Database.properties file modified
database.url1=jdbc\:mysql\://localhost\:3306/twodbone database.username1= database.password2= database.url2=jdbc\:mysql\://localhost\:3306/twodbtwo database.username2= database.driverClassName=com.mysql.jdbc.Driver
Basically, I have duplicated the code from the original file delivered by Roo to define the 2nd database. This pattern would be repeated for the other files as well.
Persistence.xml file modified
org.hibernate.ejb.HibernatePersistence org.josean.twodb.domain.DbOne true org.hibernate.ejb.HibernatePersistence org.josean.twodb.domain.DbTwo true
I duplicated the persistence unit code for the 2nd database and define unique ids. Important: Add the
as shown in the code above. As implied each entity handled by this persistence unit have to be included.
ApplicationContext.xml file modified
Same process as the other files. Duplicate as shown. Add property attribute to the
Web.xml file modified
Spring OpenEntityManagerInViewFilter1 org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter entityManagerFactoryBeanName entityManagerFactory1 Spring OpenEntityManagerInViewFilter2 org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter entityManagerFactoryBeanName entityManagerFactory2
This is it!. Application ready for deploying and testing.
I showed the interested Reader how to setup the application context of a Spring web app to access 2nd databases, in particular to Spring Roo Developer.
Get our Articles via Email. Enter your email address.