简体   繁体   中英

Using different DataBases with Spring jdbcDaoSupport

Which is the best approach to implement several different databases in one project, using Spring JdbcDaoSupport ?

I have several DB with different datasources and syntax: MySQL & Postgres , for example. In pure java-jdbc projects i used Factory Method and Abstract Factory patterns, and multiple DAOimpl classes (one for each DB) with common DAO interfaces for switch between databases. Now i use Spring-jdbc and want to implement similar behavior.

I faced the same matter two year ago and I finally choose an implementation based on a "Spring Custom Scope" ( http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes-custom ).

The spring frameworks allows multiple instances of the same bean definition to coexists together. They differ only from some contextual settings.
For instance, this bean definition will create various loginAction bean depending on the currently processed HTTP request

<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>

If you create a custom scope called "domain", you will be able to instanciate several datasource based on the same bean definition.
A datasource bean definition based on JndiObjectFactoryBean would let the servlet container manage the database connection (through the web.xml file). However, you would have to variabilize your datasource name with a Spring Property.
Beans like the database Transaction Manager must also be marked with this scope.

Next you need to activate the scope each time an HTTP request is running: I can suggest you to define the datasource name as a prefix of the request url.

Because most of web frameworks allows you to intercept HTTP requests, you can retrieve the expected datasource before processing the request.
Then, create (or reuse) a set of beans specific to the selected datasource and store it inside a ThreadLocal variable (that your custom scope implementation will rely on)

This implementation should look a little complex at first glance, but its usage appears transparent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM