多个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() { //.... }