I am using spring mvc+hibernate+two databases
So for example:
I create 2 sessionFactories. sessionFactory1
(using datasource1
) and sessionFactory2
(using datasource2
).
Would it be possible to change sessionFactory1
or sessionFactory2
to sessionFactory at runtime so that the dao/s references them. sessionFactory is already autowired to all dao/s.
I am searching for it right now I think @Configuration can help me but I am not sure.
I am trying AbstractRoutingDataSource but don't think it helps.
AbstractRoutingDataSource will work for you.
First you'll need to create a class that will store the current DB in use:
public class MyContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDBContext(String dBContext) {
contextHolder.set(dBContext);
}
public static String getDBContext() {
return (String) contextHolder.get();
}
public static void clearDBContext() {
contextHolder.remove();
}
}
You'll need to create a class that extends this one and implements determineCurrentLookupKey(), and return the current db you have in your context holder:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class MyRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return MyContextHolder.getDBContext();
}
}
See the example in http://blog.springsource.org/2007/01/23/dynamic-datasource-routing/. It worked fine for me.