databaseIdProvider实现机制
MyBatis 根据加载的数据源获取是什么厂商的数据库,并根据mapper.xml中配置的databaseId找到对应厂商的sql,不同厂商的数据库执行语句的语法以及函数存在差异。
如何配置
配置databaseIdProvider (在注入dataSource之前配置)
<bean id="vendorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="Oracle">oracle</prop>
<prop key="MySQL">mysql</prop>
</props>
</property>
</bean>
<bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider">
<property name="properties" ref="vendorProperties" />
</bean>
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="databaseIdProvider" ref="databaseIdProvider" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="configLocation" value="classpath:META-INF/spring/beans/mybatis-config.xml"></property>
<property name="mapperLocations" value="classpath*:com/ais/brm/web/mapper/**/*.xml" />
</bean>
vendorProperties 配置的是项目需要识别的厂商的数据库(上图中配置了两种 mysql 和 oracle)
databaseIdProvider 是为了让VendorDatabaseIdProvider去匹配当前的数据源
最后需要把databaseIdProvider 放置到 databaseIdProvider
配置到此结束,我们来看看我们的实现测试
<select id="queryTables" resultMap="tablesManageResult" parameterType="com.houses365.model.Tables" databaseId="mysql">
select table_name from information_schema.tables where table_schema=#{db} and table_type='base table'
<include refid="paginationSql"/>
</select>
<select id="queryTables" resultMap="tablesManageResult" parameterType="com.houses365.model.Tables" databaseId="oracle">
select table_name from user_tables
<include refid="paginationSql"/>
</select>
经过测试数据源:
mysql数据库执行上面的sql
oracle数据库执行下面的sql