spring-mybatis多数据源配置的问题

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值