使用Spring Profile和Mybatis進行多個數據源(H2和Mysql)的切換

最近在作WebMagic的後臺,遇到一個問題:後臺用到了數據庫,原本理想狀況下是用Mysql,可是爲了作到開箱即用,也整合了一個嵌入式數據庫H2。這裏面就有個問題了,如何用一套代碼,提供對Mysql和H2兩種方案的支持?博主收集了一些資料,也調試了好久,終於找到一套可行方案,記錄下來。代碼貼的有點多,主要是爲了之後方便本身查找。html

H2的使用

H2是一個嵌入式,純Java實現的數據庫,它各方面都要好於Java的sqlitejdbc。它可使用內存模式,也可使用磁盤模式。具體使用能夠看攻略:java

http://www.cnblogs.com/gao241/p/3480472.htmlmysql

爲MyBatis同時配置兩套數據源

咱們但願達到的效果是,不一樣的數據源使用不一樣的sql,而且這個切換最好只在配置中體現,與代碼無關。因此咱們選擇xml的方式編寫sql語句。git

MyBatis Spring的使用

同時使用Mybatis-Spring插件,這樣Mybatis能夠將Mapper(也就是DAO)自動配置成Bean,很是方便。它的一個完整示例能夠看這個項目:https://github.com/mybatis/jpetstore-6。這裏我配置以下:github

配置Bean

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="us.codecraft.webmagic.dao" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:/config/mapper/**/*.xml" />
    </bean>

配置Mapper

對應的DAO和配置文件以下:web

  • us.codecraft.webmagic.dao.DynamicClassDao:
public interface DynamicClassDao {

    public int add(DynamicClass dynamicClass);
}
  • DynamicClassDao.xml
<mapper namespace="us.codecraft.webmagic.dao.DynamicClassDao">

    <insert id="add" parameterType="us.codecraft.webmagic.model.DynamicClass">
      insert into DynamicClass (`ClassName`,`SourceCode`,`AddTime`,`UpdateTime`)
      values (#{className},#{sourceCode},now(),now())
    </insert>
</mapper>

使用databaseIdProvider進行多個數據源的SQL切換

MyBatis支持根據不一樣的數據庫名來進行SQL語句的切換。作法是初始化SqlSessionFactoryBean的時候,配置一個databaseIdProviderspring

<bean id="vendorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="properties">
            <props>
                <prop key="SQL Server">sqlserver</prop>
                <prop key="DB2">db2</prop>
                <prop key="Oracle">oracle</prop>
                <prop key="MySQL">mysql</prop>
                <prop key="H2">h2</prop>
            </props>
        </property>
    </bean>

    <bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider">
        <property name="properties" ref="vendorProperties"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="databaseIdProvider" ref="databaseIdProvider" />
        <property name="mapperLocations" value="classpath*:/config/mapper/**/*.xml" />
    </bean>

而後在Mapper的xml裏,把相應的語句加上databaseId="xxx"就能夠了。sql

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="us.codecraft.webmagic.dao.DynamicClassDao">

    <insert id="add" parameterType="us.codecraft.webmagic.model.DynamicClass" databaseId="mysql">
      insert into DynamicClass (`ClassName`,`SourceCode`,`AddTime`,`UpdateTime`)
      values (#{className},#{sourceCode},now(),now())
    </insert>

    <insert id="add" parameterType="us.codecraft.webmagic.model.DynamicClass" databaseId="h2">
      insert into DynamicClass (`ClassName`,`SourceCode`,`AddTime`,`UpdateTime`)
      values (#{className},#{sourceCode},now(),now())
    </insert>

</mapper>

Spring Profile

Profile是Spring 3.1後新增的特性,簡單來講,就是根據不一樣的環境,讀取不一樣的配置。這些配置能夠放在一塊兒,可是單獨生效。貼個代碼吧,很容易說明問題了:數據庫

<?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:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/WebMagic?characterEncoding=UTF-8"/>
        <property name="username" value="webmagic"/>
        <property name="password" value="webmagic"/>
    </bean>

    <beans profile="test">
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
              destroy-method="close">
            <property name="driverClassName" value="org.h2.Driver"/>
            <property name="url" value="jdbc:h2:mem:WebMagic;DB_CLOSE_DELAY=-1"/>
        </bean>
        <!--Refer to https://github.com/springside/springside4/wiki/H2-Database -->
        <jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">
            <jdbc:script location="classpath:sql/h2/schema.sql" />
            <!--<jdbc:script location="classpath:data/h2/import-data.sql" encoding="UTF-8"/>-->
        </jdbc:initialize-database>
    </beans>

    <beans profile="standalone">
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
              destroy-method="close">
            <property name="driverClassName" value="org.h2.Driver"/>
            <property name="url" value="jdbc:h2:file:~/.h2/WebMagic;AUTO_SERVER=TRUE"/>
        </bean>
        <!--Refer to https://github.com/springside/springside4/wiki/H2-Database -->
        <jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">
            <jdbc:script location="classpath:sql/h2/schema.sql" />
            <!--<jdbc:script location="classpath:data/h2/import-data.sql" encoding="UTF-8"/>-->
        </jdbc:initialize-database>
    </beans>

</beans>

設置Profile有不一樣的方式。apache

在JUnit裏面,使用註解@ActiveProfile便可。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/config/spring/applicationContext*.xml"})
@ActiveProfiles("test")
@Transactional
public abstract class AbstractTest {
}

Web項目則是在web.xml裏設置:

<init-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>product</param-value>
</init-param>

如此配置,就能夠達到在不一樣的環境使用不一樣bean的目的!

參考資料

相關文章
相關標籤/搜索