Spring+Mybatis 多数据源配置

时间:2022-04-21 05:14:28

同一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中匹配时,会找不到相应方法,而报错!!!

<property name = "basePackage" value = "com.business.*.*dao1"/> 
//配置dao层需注入的sessionFactory
<property name = "sqlSessionFactoryBeanName" value = " sqlSessionFactoryBean1"/>

</bean>

mapperScanner2:

<bean id="mapperScanner2" class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<property name = "basePackage" value = "com.business.*.*dao2"/> 
<property name = "sqlSessionFactoryBeanName" value = " sqlSessionFactoryBean2"/>

</bean>


其他配置:事物配置(dataSourceTransactionManager),持久化模板(SqlSessionTemplate


常见错误1:

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://*.com/questions/4746766/spring-and-mybatis-multiple-data-sources-setup

SpringBoot 版本多数据源实现:https://blog.csdn.net/neosmith/article/details/61202084

github代码实现:https://github.com/Wangdali123/springboot-datasources

动态切换填坑版完整代码:http://blog.csdn.net/xiazai353503200/article/details/79390879