同一applicationContext.xml中:
1,配置多個數據源(採用連接池c3p0,直接jdbc連也行)
數據源1:dataSource1
<bean id = "dataSource1" class= "com.mchange.v2.c3p0.ComboPooledDataSource" lazy-init = "default">
<property name="driverClass" value = ""/>
...
...
</bean>
數據源2:dataSource2
<bean id = "dataSource2" class= "com.mchange.v2.c3p0.ComboPooledDataSource" lazy-init = "default">
<property name="driverClass" value = ""/>
...
...
</bean>
2, 配置mybatis數據會話管理(sqlSessionFactoryBean)
會話factory1:sqlSessionFactoryBean1
<bean id = "sqlSessionFactoryBean1" class = "mybatis.spring.SqlSessionFactoryBean">
<property name = "mapperLocations">
<list>
//不同factory,儘量保持其mapper的路徑不同
<value>classpath:mapper/*Mapper.xml</value> //classpath指的是:src/main/resources(maven項目文件包結構哦)
</list>
</property>
<property name = "dataSource" ref = "dataSource1"></property>
</bean>
會話factory2:sqlSessionFactoryBean2
<bean id = "sqlSessionFactoryBean2" class = "mybatis.spring.SqlSessionFactoryBean">
<property name = "mapperLocations">
<list>
<value>classpath:mapper/*Mapper.xml</value>
</list>
</property>
<property name = "dataSource" ref = "dataSource2"></property>
</bean>
3, 配置Dao接口層(重點注意)
mybatis用mapperScannerConfigurer掃描相關的dao(或mapper)的interface的包,將其注入到spring進行管理;
dao層需要注入第2步配置的sessionFactory來獲得session(session中加入事物等操作),跟sessionFactory中配置的*Mapper.xml進行一一匹配;
mapperScanner1:
<bean id="mapperScanner1" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
//不同數據源的掃描dao層不要放在一起,不然數據源1掃描了數據源2的dao,那 去數據源1的mappe.xml中匹配時,會找不到相應方法,而報錯!!!
</bean>
mapperScanner2:
<bean id="mapperScanner2" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
</bean>
其他配置:事物配置(dataSourceTransactionManager),持久化模板(SqlSessionTemplate)
No unique bean of type [org.apache.ibatis.sessioin.SqlSessionFactory] is defined:expected single matching bean but found 2:[sqlSessionFactoryBean1,sqlSessionFactoryBean2]
解決問題:檢查步驟3配置,是否有配置sqlSessionFactoryBeanName
常見錯誤2:
...Dao conflicts with existing, non-compatible bean definition of same name and class[org.mybatis.spring.mapper.MapperFactoryBean]
解決問題:檢查步驟3配置,屬性basePackage,兩個數據源是否掃描了同一dao層包,若是,更改dao層包,不同數據源需掃描不同的dao層包。
參考:http://stackoverflow.com/questions/4746766/spring-and-mybatis-multiple-data-sources-setup