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.Veendor DatabaseIdProviderに適用する必要があります。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文は少し違っています。プロファイルconfig.propertiesのdata Sourceフィールドがmysqlまたはoraceに設定されているときに、対応する結果が得られます。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文に対応しています。oraceはdatabased=oraceの構成です。あるいは、両データベースのユーザーテーブルのデータが同じであれば、テストケースによって印刷されたユーザ名の一つは順で一つは倒順であり、同様の結論が得られる。
   
最後にappication Contect.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>