簡體   English   中英

MyBatis如何為不同的數據庫后端生成不同的SQL

[英]MyBatis how can I generate different sql for different database backend

我將mybatis-spring 1.2.3和Spring4一起使用來創建Web應用程序。 主要數據存儲是生產環境中的MySQL,但我還在單元測試中使用內存數據庫H2。

MyBatis在測試和生產中都可以與MySQL和H2很好地兼容,但是遇到一個問題,有一天我需要在對MySQL的查詢中使用force index(idx1) ,這將導致單元測試中出現語法錯誤,因為H2 hasn不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>

請在此處此處查看相關文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM