首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

MyBatis Between And 參數綁定錯誤:parameterType 應為 Map 而非單一 Integer

     編輯:程式設計疑難解答

錯誤現象

<select id="selectByTwoId" resultMap="BaseResultMap" parameterType="java.lang.Integer">
    select <include refid="Base_Column_List" />
    from message
    where id between #{ido,jdbcType=INTEGER} and #{idt,jdbcType=INTEGER}
</select>

DAO 方法:List selectByTwoId(Integer ido, Integer idt);
報錯:Parameter 'ido' not found. Available parameters are [0, 1, param1, param2]

原因分析

MyBatis 對多參數方法的默認命名規則:

  • 無 @Param 註解時:參數名為 param1, param2... 或 0, 1...(取決於版本)。
  • XML 中使用 #{ido} 找不到匹配參數,故報錯。

三種解決方案

方案一:加 @Param 註解(推薦,最簡單)

// Mapper 接口
List selectByTwoId(@Param("ido") Integer ido, @Param("idt") Integer idt);

XML 保持不變,#{ido}、#{idt} 直接匹配。

方案二:parameterType 改為 Map,DAO 手動裝填

<select ... parameterType="map"> ... #{ido} ... #{idt} </select>

// DAO 實現
public List selectByTwoId(Integer ido, Integer idt) {
    Map params = new HashMap<>();
    params.put("ido", ido);
    params.put("idt", idt);
    return sqlSession.selectOne("namespace.selectByTwoId", params);
}

適用於動態參數數量不固定的場景。

方案三:封裝參數對象


public class IdRange {
    private Integer ido;
    private Integer idt;
    // getter/setter
}

// Mapper
List selectByTwoId(IdRange range);

// XML parameterType="com.xxx.IdRange"
#{ido} #{idt} 直接對應屬性

適合參數復雜、復用率高的情況。

最佳實踐建議

  1. 優先使用 @Param:零侵入、代碼清晰、MyBatis 3.4.1+ 完美支持。
  2. 避免 parameterType="java.lang.Integer" 接收多參數:單一值類型只能映射單參數。
  3. 啟用 useActualParamName (MyBatis 3.4.1+):在配置中 <setting name="useActualParamName" value="true"/>,配合 Java 8 編譯參數 -parameters,可省略 @Param 直接使用形參名。

總結

多參數映射失敗核心在於 MyBatis 默認參數名 (param1/param2) 與 XML 佔位符 (ido/idt) 不匹配。添加 @Param 註解是成本最低、可讀性最好的修復方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved