MyBatis如何为不同的数据库后端生成不同的sql

时间:2015-11-10 09:44:44

标签: java spring-boot h2 mybatis spring-mybatis

我正在使用mybatis-spring 1.2.3和Spring4来创建一个Web应用程序。主数据存储是生产环境中的MySQL,但我也在单元测试中使用内存数据库H2。

MyBatis在测试和生产中同时适用于MySQL和H2,但是我遇到了一个问题,即有一天我需要在MySQL的查询中使用force index(idx1),这将导致单元测试中出现语法错误因为H2不支持force index。结果,单元测试完全被打破了。

我想知道MyBatis有什么方法可以处理这种情况吗? (数据库的类型在测试和生产方面有所不同,它们对SQL语法的支持也不尽相同。)

这是我的映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="myproject.mapper.UserMapper">
  <select id="getGameUsersForDate" resultType="myproject.dao.domain.GameUser">
    select
    *
    from game_user
    force index(idx1)
    where
    game_id in
    <choose>
      <when test="gameIds.size() > 0">
        <foreach item="gameId" collection="gameIds" open="(" separator="," close=")">
          #{gameId}
        </foreach>
      </when>
      <otherwise>
        (null)
      </otherwise>
    </choose>
    and uid in
    <choose>
      <when test="uids.size() > 0">
        <foreach item="uid" collection="mids" open="(" separator="," close=")">
          #{mid}
        </foreach>
      </when>
      <otherwise>
        (null)
      </otherwise>
    </choose>
    and `date` = #{date}
  </select>
</mapper>

1 个答案:

答案 0 :(得分:3)

MyBatis提供了多数据库供应商支持,允许您根据您使用的数据库供应商以不同方式构建SQL。因此,您可以将有问题的代码包装在测试中,例如:

<if test="_databaseId == 'mysql'">
   force index(idx1)
</if>

请参阅相关文档herehere