I have two databases: test and test1. Both databases have a table TEST_ONEapplicationContext.xml. The configuration of the table TEST_ONEapplicationContext.xml is as follows // database test configuration & lt; beanid & quot; test & quot; class & quot; org. springframework. jdbc. datasource. driverManager
I have two databases, test and test1. Both databases have a table named TEST_ONE.
The configuration of applicationContext. xml is as follows:
// Configure database test
Class = "org. springframework. jdbc. datasource. DriverManagerDataSource">
// Configure database test1
Class = "org. springframework. jdbc. datasource. DriverManagerDataSource">
// Integrate two data sources and specify the data source management class
// Set the default data source configuration
Class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean">
Org. hibernate. dialect. MySQLDialect
Com/keith/vo/TestOne. hbm. xml
Tool class for data source switching:
Public class DBContextHolder {
// Database test
Public static final StringDB_TEST = "test ";
// Database test1
Public static final StringDB_TEST_1 = "test1 ";
Private static finalThreadLocalCON_LOCAL = new ThreadLocal ();
Public static voidsetDB (String type ){
CON_LOCAL.set (type );
}
Public static StringgetDB (){
Return (String) CON_LOCAL.get ();
}
Public static voidclearDB (){
CON_LOCAL.remove ();
}
}
// This class is used to manage the data source, in the configuration file
Public class DynamicDataSource extendsAbstractRoutingDataSource {
@ Override
ProtectedObject determineCurrentLookupKey (){
// TODOAuto-generated method stub
Return DBContextHolder. getDB ();
}
}
// Compile the test class
Public class Test {
Publicstatic void main (String [] args ){
ApplicationContext context = newClassPathXmlApplicationContext ("applicationContext. xml ");
// Dynamically set the data source
DBContextHolder. setDB (DBContextHolder. DB_TEST_1 );
SessionFactory sf = (SessionFactory) context. getBean ("sessionFactory ");
Session s = sf. openSession ();
Transactiontr = s. getTransaction ();
Tr. begin ();
TestOneone = new TestOne ();
One. setName ("aaa ");
S. save (one );
Tr. commit ();
Sf. close ();
}
}