我现在的系统需要调用一个数据库中的用户表,其它的系统业务表又是在另一个数据库中,当我在登陆的时候是调用的一个数据库的表,进入系统后又是调用另一个数据库中的表,   这种情况下,程序怎么去分配数据源啊,我听说首先在spring中配置两个数据源(测试中),但是程序中具体是怎么去调用的呢? 
帮忙举个例子,谢了,

解决方案 »

  1.   

    context.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
    http://www.springframework.org/schema/jee    
                    http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
    <jee:jndi-lookup id="mysqlds" jndi-name="java:comp/env/jdbc/mysqlds" />
    <jee:jndi-lookup id="orads" jndi-name="java:comp/env/jdbc/orads" />
    <bean id="dataSource" class="util.DynamicDataSource">
    <property name="targetDataSources">
    <map key-type="java.lang.String">
    <entry key="0" value-ref="mysqlds" />
    <entry key="1" value-ref="orads" />
    </map>
    </property>
    <property name="defaultTargetDataSource" ref="orads" />
    </bean>DynamicDataSource。java:import java.sql.SQLException;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource {  
    //static Logger log = Logger.getLogger("DynamicDataSource");  
    @Override  
    protected Object determineCurrentLookupKey() {  
    // TODO
    return DbContextHolder.getDbType();  
    } @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
    // TODO Auto-generated method stub
    return false;
    } @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
    // TODO Auto-generated method stub
    return null;
    }
    }DbContextHolder。java 
    public class DbContextHolder {
    private static final ThreadLocal contextHolder = new ThreadLocal(); public static void setDbType(String dbType) {
    contextHolder.set(dbType);
    } public static String getDbType() {
    return (String) contextHolder.get();
    } public static void clearDbType() {
    contextHolder.remove();
    }
    }
    程序引用:
    调用mysqlds
    DbContextHolder.setDbType("1");  
                UserDomain od = this.testService.queryUserAccount("admin");            System.out.println("username=="+od.getName());
                
     调用orads           
                DbContextHolder.setDbType("0");  
                 od = this.testService.queryUserAccount("admin");
                System.out.println("username=="+od.getName());