Spring+Mybatis多数据源配置(二)——databaseIdProvider的使用

 在上一篇同系列的博文中,讲到配置多数据源,然后根据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>
时间: 2024-08-08 06:01:08

Spring+Mybatis多数据源配置(二)——databaseIdProvider的使用的相关文章

Spring+Mybatis多数据源配置(一)——MySQL与Oracle通过配置切换

在小型项目中,一般配置一个数据库,也就是一个mybatis数据源,但是有时候需要同时支持两种数据库,比如mysql和oracle. 最笨的方法就是配置两个spring配置文件,然后根据不同的部署,采用不同的配置文件,其实这两个配置文件可以合成一个配置文件,通过java的properties文件进行配置. 首先说明下配置单个数据库,也就是单个数据源的配置. 首先看一下spring的配置文件applicationContext.xml(这里采用的是spring+mybatis,所以有关数据库的及my

Spring+Mybatis多数据源配置(三)——Spring如何获取Properties文件的信息

严格来说,本博文所阐述的内容和这个系列来说,没有什么必要的关系,本博文的主题是:如何使用spring获取properties文件的信息.本博文所采用的用例都和这个系列有关,所以就放在这里讲了. 通过spring的配置(applicationContext.xml),如:<context:property-placeholder location="classpath:config.properties"/>(具体位置可以参考本系列的前两篇博文),这个就配置了spring自动

Spring+Mybatis多数据源配置(四)——AbstractRoutingDataSource实现数据源动态切换

有时候需要在程序中动态切换数据源,那么这个系列的之前的博文所阐述的方法就不再使用了,总不能通过程序更改config.properties文件的dataSource的值,然后再重启web服务器以便加载applicationContext.xml文件.这里讲诉的是如何利用AbstractRoutingDataSource进行数据源动态切换. 首先上applicationContext.xml文件: <?xml version="1.0" encoding="UTF-8&qu

spring mybatis多数据源实例详解_java

同一个项目有时会涉及到多个数据库,也就是多数据源.多数据源又可以分为两种情况: 1)两个或多个数据库没有相关性,各自独立,其实这种可以作为两个项目来开发.比如在游戏开发中一个数据库是平台数据库,其它还有平台下的游戏对应的数据库: 2)两个或多个数据库是master-slave的关系,比如有mysql搭建一个 master-master,其后又带有多个slave:或者采用MHA搭建的master-slave复制: 目前我所知道的 Spring 多数据源的搭建大概有两种方式,可以根据多数据源的情况进

spring boot druid mybatis 多数据源 配置

spring boot 在配置时做了很多简化配置的设置,但是简化的配置往往已牺牲一定的定制化,比如在数据源的配置时,spring boot 只提供4种数据库连接池的配置,其中并不支持常用的druid 阅读spring boot DataSourceBuilder 的源码可以发现 spring boot 提供的4种数据源类型并不是我们想要的 private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] { "org.apac

spring+mybatis多数据源配置问题,谁能帮我分析一下问题出在哪儿

问题描述 配置的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:aop="http://www.springframework

Spring-Boot + Mybatis 多数据源配置

折腾了一天,终于完成了多数据源的配置,记录在这里! 1,先上SpringBoot 基础配置         ①,系统引入了Security的包,但是没有配置Security相关信息,在启动时会打印警告log,故这里排除SecurityAutoConfiguration这个类 2,配置两个数据源 @Configuration public class DataBaseConfig implements EnvironmentAware { private RelaxedPropertyResolv

spring mvc-关于springMVC mybatis 多数据源配置问题

问题描述 关于springMVC mybatis 多数据源配置问题 12:59:38,349 ERROR [STDERR] SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder] 12:59:38,382 WARN [ConfigurationClassEnhancer] @Bean method SpringIocMappingConfig.mapperScannerC

spring mybatis 的注解事务

首先要在 spring-mybatis的配置文件添加 事务支持,和事务annotation支持 注意:如果是mysql请使用innodb innodb 支持事务功能,myisam 不支持. <!-- transaction support--> <!-- PlatformTransactionMnager --> <bean id="txManager" class="org.springframework.jdbc.datasource.Dat