我正在使用 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> 

请您参考如下方法:

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

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

参见相关文档herehere .


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!