Spring和Mybatis设置了多个数据源

时间:2011-01-20 11:51:33

标签: spring datasource mybatis

我的应用程序使用Spring3 + MyBatis3。我正在尝试为它设置多个数据源。设置如下:

<!-- 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>

在日志中,我发现了这条消息:

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

我用Google搜索并查看mybatis手册,但无法找到如何使用mybatis设置多个数据源的方法。 有什么想法吗?

3 个答案:

答案 0 :(得分:4)

也解决了!只需在MapperScannerConfigurer中引用工厂bean:s​​qlSessionFactoryBeanName

第一个数据源&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;

<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<bean id="sqlSessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource1"/>
</bean>

<bean id="MapperScannerConfigurer1" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.package.p1"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory1"/>
    </bean>

第二个数据源&gt;&gt;&gt;&gt;&gt;&gt;

<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
<bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource2"/>
    </bean>
<bean id="MapperScannerConfigurer1" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.package.p2"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2"/>
</bean>

答案 1 :(得分:2)

解决了,问题是我必须直接引用 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"/>

答案 2 :(得分:0)

在DAO实施中,使用SqlSessionTemplate代替SqlSessionDaoSupport。注入bean db1SqlSessionTemplatedb2SqlSessionTemplate

@Repository
public class TestDaoImpl implements TestDao{
    @Autowired
    private SqlSession db1SqlSessionTemplate;
    ...
    db1SqlSessionTemplate.selectList("testSelect");
    ...
}

在扩展SqlSessionDaoSupport时,Spring不知道您使用SqlSession