4

我的应用程序使用 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]

我用谷歌搜索并查看了 mybatis 手册,但找不到如何使用 mybatis 设置多个数据源的方法。有任何想法吗?

4

3 回答 3

4

也解决了!只需在 MapperScannerConfigurer 中引用您的工厂 bean: sqlSessionFactoryBeanName

第一个数据源>>>>>>>

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

第二数据源>>>>>>

<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>
于 2014-12-11T14:17:09.333 回答
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"/>
于 2011-01-20T13:08:04.230 回答
0

在 DAO 实现中使用SqlSessionTemplate而不是SqlSessionDaoSupport. 注入 beandb1SqlSessionTemplatedb2SqlSessionTemplate.

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

当扩展SqlSessionDaoSupport上下文时 Spring 不知道你使用SqlSession.

于 2015-05-13T02:57:15.517 回答