首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

MyBatis foreach 遍歷報錯 `_frch_item_0 not found` 根因與解決方案

     編輯:Java 相關知識

常見錯誤現象

There is no getter for property named 'states' in 'class com.xingguo.model.User'

或 _frch_item_0 not found,通常發生在 `` 動態 SQL 中。

三大核心錯誤原因

  1. 參數類型非 List/集合:實體類中包含 List 屬性時,collection 指定錯誤
  2. 遍歷屬性名/字段名錯誤:`item`、`index` 不匹配實際對象結構
  3. 多參數未用 @Param 命名:導致參數順序混亂,MyBatis 無法正確綁定

源碼級分析:MyBatis 參數包裝機制

關鍵方法:DefaultSqlSession.wrapCollection()

private Object wrapCollection(final Object object) {
    if (object instanceof Collection) {
        StrictMap<Object> map = new StrictMap<>();
        map.put("collection", object);           // 默認 key: "collection"
        if (object instanceof List) {
            map.put("list", object);             // List 額外 key: "list"
        }
        return map;
    } else if (object != null && object.getClass().isArray()) {
        StrictMap<Object> map = new StrictMap<>();
        map.put("array", object);                // 數組 key: "array"
        return map;
    }
    return object; // 單個對象直接返回
}

核心結論

  • **單參數為 List/Collection**:SQL 中直接用 `` 或 `collection="collection"`
  • **單參數為數組**:用 `collection="array"`
  • **實體類包含 List 屬性**:必須指定 `collection="屬性名"`(如 `collection="states"`)
  • **多參數場景**:**強制使用 `@Param` 註解**命名每個參數,SQL 中引用對應名稱

正確示例

場景 1:單參數 List

// Mapper 接口
List<User> selectByIds(@Param("ids") List<Long> ids);

// XML
<select id="selectByIds" resultType="User">
    SELECT * FROM user
    <where>
        <foreach collection="ids" item="id" separator="," open="id IN (" close=")">
            #{id}
        </foreach>
    </where>
</select>

場景 2:實體類包含 List 屬性

public class QueryParam {
    private List<Long> ids; // getter/setter
}

// Mapper
List<User> selectByParam(QueryParam param);

// XML - 必須指定 collection="ids"
<foreach collection="ids" item="id" ...> #{id} </foreach>

場景 3:多參數必加 @Param

// 錯誤:無 @Param,參數名丟失
List<User> select(User user, List<Long> ids);

// 正確
List<User> select(@Param("user") User user, @Param("ids") List<Long> ids);

// XML 引用
<foreach collection="ids" ...>
<if test="user.name != null">...

調試技巧

  1. 開啟 MyBatis 日誌(`log4j.logger.org.apache.ibatis=DEBUG`)查看實際 SQL 綁定參數
  2. 在 `` 中添加 `open/close/separator` 避免 SQL 語法錯誤
  3. 使用 `item` 變量名避免與外層屬性衝突
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved