在上一篇同系列的博文中,讲到配置多数据源,然后根据config.properties配置不同的数据库,进行切换。而且需要根据不同的数据库,配置不同的mybatis sql映射配置文件,如下:
<property name="mapperLocations"> <list> <value>classpath:com/shr/dao/resources/${dataSource}mappers/*_mapper.xml</value> </list> </property>
这样根据dataSource名称匹配不同的mybatis sql映射配置文件,大家都知道mysql和oracle是有一些语法差异的,但是大多数的语法是一样的,我们能否只针对这些有语法差异的sql语句进行多重配置,其余的相同的语法的就使用同一份配置呢?答案当然是肯定的。
这里需要应用到mybatis的org.apache.ibatis.mapping.VendorDatabaseIdProvider。通过在mybatis sql映射配置文件中添加databaseId的属性,来区分不同的数据库。
举个例子:
<resultMap id="userResultMap" type="com.shr.dao.model.userManage.UserInfo"> <result property="user_id" column="user_id"/> <result property="user_name" column="user_name"/> <result property="user_password" column="user_password"/> <result property="user_privilege" column="user_privilege"/> <result property="user_alias" column="user_alias"/> <result property="create_date" column="create_date" javaType="java.util.Date" jdbcType="TIMESTAMP"/> <result property="invalid_date" column="invalid_date" javaType="java.util.Date" jdbcType="TIMESTAMP"/> </resultMap> <select id="selectUserInfo" resultMap="userResultMap" databaseId="mysql"> select user_id, user_name, user_password, user_privilege, user_alias, create_date, invalid_date from user_define order by user_id asc </select> <select id="selectUserInfo" resultMap="userResultMap" databaseId="oracle"> select user_id, user_name, user_password, user_privilege, user_alias, create_date, invalid_date from user_define order by user_id desc </select>
上面是一个获取用户信息的sql语句,可以看到mysql和oracle的sql语句有略微的差异(asc和desc),当配置文件config.properties中的dataSource字段配置为mysql或者为oracle时都可以获取相应的结果。当dataSource配置为oracle然后在上面的代码中删掉:
<select id="selectUserInfo" resultMap="userResultMap" databaseId="oracle"> select user_id, user_name, user_password, user_privilege, user_alias, create_date, invalid_date from user_define order by user_id desc </select>
这一段内容,运行测试用例:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:WebContent/WEB-INF/applicationContext.xml") @Transactional @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=false) public class UserManageServiceTest { @Inject private UserManageService userManageService; @Test public void testGetUserListInfo() { List<UserListInfo> list = userManageService.getUserListInfo(); for(UserListInfo user : list) { System.out.println(user.getUser_name()); } } }
会报如下错误:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.shr.dao.mapper.IuserManageMapper.selectUserInfo at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:189) at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:43) at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:58) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:51) at com.sun.proxy.$Proxy29.selectUserInfo(Unknown Source) at com.shr.service.userManage.UserManageService.getUserListInfo(UserManageService.java:98) at com.shr.service.userManage.UserManageServiceTest.testGetUserListInfo(UserManageServiceTest.java:35) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
通过报错信息,大概可以知道没有相应的配置映射关系。由此可以证明(把config.properties中的dataSource配置成mysql然后删掉databaseId="mysql"的配置,结果也会报相同的错误),mysql对应的是databaseId="mysql"的sql语句,而oracle对应的是databaseId="oracle"的配置语句。或者如果两个数据库中用户表数据是相同的话,通过测试用例打印出来的用户名称一个是正序一个是倒序,也可以得出相同的结论。
最后奉上applicationContext.xml的配置:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd http://www.springframework.org/schema/aop classpath:/org/springframework/aop/config/spring-aop-3.0.xsd http://www.springframework.org/schema/context classpath:/org/springframework/context/config/spring-context-3.0.xsd http://www.springframework.org/schema/tx classpath:/org/springframework/transaction/config/spring-tx-3.0.xsd"> <!-- IoC配置 --> <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 --> <context:component-scan base-package="com.shr.dao" /> <context:component-scan base-package="com.shr.service" /> <!-- DAO配置 --> <context:property-placeholder location="classpath:config.properties"/> <bean id="mysql" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${mysql_driver}"/> <property name="url" value="${mysql_url}"/> <property name="username" value="${mysql_username}"/> <property name="password" value="${mysql_password}"/> </bean> <bean id="oracle" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${ora_driver}"/> <property name="url" value="${ora_url}"/> <property name="username" value="${ora_username}"/> <property name="password" value="${ora_password}"/> </bean> <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> <bean name="myBatisSQLInterceptor" class="com.shr.dao.MyBatisSQLInterceptor"></bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="${dataSource}" /> <property name="typeAliasesPackage" value="com.shr.dao.pojo,com.shr.dao.model" /> <property name="databaseIdProvider" ref="databaseIdProvider" /> <property name="mapperLocations"> <list> <value>classpath:com/shr/dao/resources/mappers/*_mapper.xml</value> </list> </property> <!-- <property name="configLocation" value="/WEB-INF/mybatis-config.xml"/> --> <property name="typeHandlersPackage" value="com.shr.dao" /> <property name="plugins"> <list> <ref bean="myBatisSQLInterceptor"/> </list> </property> </bean> <!-- 配置事务管理器 --> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="${dataSource}"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.shr.dao.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- <property name="markerInterface" value="com.shr.dao.mapper.ITemplateMapper"/> --> </bean> </beans>