Search code examples
springdatasourcemybatis

Spring and Mybatis multiple data sources setup


My applications uses Spring3+MyBatis3. I'm trying to setup multiple data source for it. Setup looks like:

<!-- db1 setup-->
<bean id="db1SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
    p:configLocation="WEB-INF/mybatis/sqlMapConfig.xml"
    p:dataSource-ref="db1DataSource" />
<bean id="db1SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="db1SqlSessionFactory"/>
</bean>
<!-- db2 setup -->
<bean id="db2SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
    p:configLocation="WEB-INF/mybatis/sqlMapConfig.xml"
    p:dataSource-ref="db2DataSource" />
<bean id="db2SqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="db2SqlSessionFactory"/>
</bean>

In the logs, I've found this message:

No unique bean of type [org.apache.ibatis.session.SqlSessionFactory] is defined: expected single matching bean but found 2: [db1SqlSessionFactory, db2SqlSessionFactory]

I googled and looked into mybatis manuals but couldn't find way how to setup multiple data sources with mybatis. Any ideas?


Solution

  • solved, the problem was that I must specify directly reference to sqlSessionFactory

    <bean id="myDao" class="org.mybatis.spring.mapper.MapperFactoryBean"
        p:sqlSessionTemplate-ref="db1SqlSessionTemplate"
        p:mapperInterface="my.project.domain.dao.MyDao"
        p:sqlSessionFactory-ref="db1SqlSessionFactory"/>