Mapper 接口方法接收 Map 參數,XML 中 parameterType="map",SQL 里用 #{account},這個 account 值從哪來?
// 接口
int countUser(Map params);
// 調用
Map map = new HashMap<>();
map.put("account", "user123");
map.put("status", 1);
mapper.countUser(map);
map.get("key")<select id="countUser" resultType="int" parameterType="map">
SELECT COUNT(*) FROM users
WHERE account = #{account}
AND status = #{status}
</select>
| 錯誤現象 | 原因 | 解決 |
|---|---|---|
| BindingException: Parameter 'account' not found | Map 中無 "account" key | 調用方 put 正確 key |
| SQL 執行結果為 0 | key 拼寫不一致 (account vs acount) | 檢查 key 拼寫大小寫 |
| 類型轉換異常 | Map value 類型與數據庫列類型不匹配 | 確保 put 正確類型值 |
// 接口
int countUser(@Param("account") String account, @Param("status") Integer status);
// XML 中直接用 #{account}, #{status}
// 無需 Map 包裝,代碼更清晰
@Param("param") UserQueryDTO dto#{account} 的值來自調用方傳入 Map 中 put 的 "account" 鍵值。MyBatis 以 Map 作為參數上下文,OGNL 表達式解析 #{key} 時調用 map.get("key")。確保調用方、XML、SQL 三處 key 名稱完全一致是關鍵。