水下功夫做透,水上才能顺风顺水。

MyBatis: databaseId的用法

可以通过databaseId来区分执行的SQL是在MySQL上还是在Oracle上。
一、在配置文件mybatis-config中配置databaseId:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties>
        <property name="username" value="root"/>
    </properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="cn.edu.tju.domain"/>
    </typeAliases>
    <environments default="oracle">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://xx.xx.xx.xx/test"/>
                <property name="username" value="${username}"/>
                <property name="password" value="MyPassword"/>
            </dataSource>
        </environment>

        <environment id="oracle">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@xx.xx.xx.xx:50011:ADC"/>
                <property name="username" value="adcepis_test"/>
                <property name="password" value="adcepis_test"/>
            </dataSource>
        </environment>
    </environments>
    <databaseIdProvider type="DB_VENDOR">
        <property name="MySQL" value="mysql"/>
        <property name="Oracle" value="oracle"/>
    </databaseIdProvider>
    <mappers>
 <!--       <package name="cn.edu.tju.mapper"/>-->
        <mapper resource="mapper/UserMapper.xml"/>

    </mappers>

</configuration>

二、根据不同的数据库语法写不同的SQL语句并配置相同的id

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.edu.tju.mapper.UserMapper">
    <select id="selectStudent" resultType="cn.edu.tju.domain.Student" databaseId="mysql">
        select * from student where username = #{username} limit 1
    </select>

    <select id="selectStudent" resultType="cn.edu.tju.domain.Student" databaseId="oracle">
        select * from student where name = #{username} and rownum<2;
    </select>
</mapper>

这样,当MyBatis运行时,会根据当前的数据库是Oracle还是MySQL来匹配不同的SQL语句来执行。

posted @ 2024-04-19 10:00  北方寒士  阅读(1311)  评论(0编辑  收藏  举报