多個mapper location時, mybatis spring的自動掃描配置


1. MapperScannerConfigurer 里面的basePackage, 多個package用逗號分隔

2. SqlSessionFactoryBean里面的mapperLocations, 用<list><value></value>...</list>設置

例如:

<bean id="propertyConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:database.properties</value>
            </list>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="poolPreparedStatements" value="true" />
        <property name="initialSize" value="1" />
        <property name="maxActive" value="20" />
        <property name="maxIdle" value="5" />
        <property name="validationQuery" value="select 1" /><!-- This one is for MySQL -->
        <!--<property name="validationQuery" value="select 1 from dual" /> This one is for Oracle -->
        <property name="testOnBorrow" value="true" />
        <property name="testWhileIdle" value="true" />
    </bean>

    <bean id="dataSourceLocal" parent="dataSource">
        <property name="driverClassName" value="${db.mysql.local.driver}" />
        <property name="url" value="${db.mysql.local.url}" />
        <property name="username" value="${db.mysql.local.user}" />
        <property name="password" value="${db.mysql.local.password}" />
    </bean>

<!-- 當有多個數據源時, 自sqlSessionFactory, mapperScannerConfigurer 到 transactionmanager, 都要設置兩套id --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.rockbb.facility.common.dao.mapper, com.rockbb.facility.weixin.dao.mapper" />
<!-- 當只有一個數據源時,這行可以不寫. -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSourceLocal" /> <property name="mapperLocations"> <list> <value>classpath:com/rockbb/facility/common/dao/mapper/*.xml</value> <value>classpath:com/rockbb/facility/weixin/dao/mapper/*.xml</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSourceLocal" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" />

關於詳細的配置項說明, 參考 http://haohaoxuexi.iteye.com/blog/1843309

當多個數據源都要使用事務時, 要這樣定義

<tx:annotation-driven transaction-manager="transactionManagerA" />
<tx:annotation-driven transaction-manager="transactionManagerB" />

在代碼中, 如果不顯式指明使用哪個事務, 則默認使用先聲明的那個, 本例中就是 transactionManagerA
顯式指明使用哪個事務管理, 需要用這樣的注解

@Transactional("transactionManagerB")
public void doSomething() {
    //....
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM