MyBatis如何为不同的数据库后端生成不同的SQL
我将mybatis-spring
1.2.3和Spring4一起使用来创建Web应用程序。主要数据存储是生产环境中的MySQL,但我还在单元测试中使用内存数据库H2。
MyBatis在测试和生产中都可以与MySQL和H2一起很好地工作,但是我遇到一个问题,有一天我需要force
index(idx1)在对MySQL的查询中使用,由于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>
回答:
MyBatis提供了多数据库供应商支持,使您可以根据所使用的数据库供应商来不同地构造SQL。因此,您可以将有问题的代码包装在测试中,例如:
<if test="_databaseId == 'mysql'">   force index(idx1)
</if>
请在此处和此处查看相关文档。
以上是 MyBatis如何为不同的数据库后端生成不同的SQL 的全部内容, 来源链接: utcz.com/qa/426108.html
