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

Struts2 + MyBatis:NumberFormatException: null 異常排查與 1對多關聯查詢最佳實踐

     編輯:程式設計疑難解答

異常現場

Action 中 Integer.parseInt(request.getParameter("ftId")) 拋出 NumberFormatException: null,導致教師公寓關聯查詢失敗。

根因分析

  1. 參數名不匹配:前端傳參名(如 apartmentId)與後端 getParameter("ftId") 不一致,取得 null。
  2. 未驗證參數存在性:直接解析 null 字符串導致異常。
  3. 1對多映射配置缺失:MyBatis ResultMap 未正確配置 <collection>,導致關聯集合為空。

修正方案

1. 參數獲取防禦性編程

String ftIdStr = ServletActionContext.getRequest().getParameter("ftId");
if (ftIdStr == null || ftIdStr.trim().isEmpty()) {
    // 返回錯誤提示或預設值
    return;
}
int ftId = Integer.parseInt(ftIdStr);

2. MyBatis 1對多 ResultMap 配置

<resultMap id="TeacherApartmentResult" type="TeacherApartment">
    <id property="id" column="ap_id"/>
    <result property="name" column="ap_name"/>
    <collection property="teachers" ofType="Teacher">
        <id property="id" column="t_id"/>
        <result property="name" column="t_name"/>
    </collection>
</resultMap>

<select id="findTeacher" resultMap="TeacherApartmentResult">
    SELECT ap.id AS ap_id, ap.name AS ap_name,
           t.id AS t_id, t.name AS t_name
    FROM teacher_apartment ap
    LEFT JOIN teacher t ON t.apartment_id = ap.id
    WHERE ap.id = #{id}
</select>

3. Service 層簡化

public List<Teacher> findTeacher(int id) {
    try (SqlSession session = MyBatisUtils.getSqlSession()) {
        TeacherApartmentDaoMapper mapper = session.getMapper(TeacherApartmentDaoMapper.class);
        TeacherApartment ap = mapper.findTeacher(id); // 返回包含教師列表的公寓對象
        return ap != null ? ap.getTeachers() : Collections.emptyList();
    }
}

關鍵檢查清單

  • ☐ 前端表單/JS 傳參名 = 後端 getParameter 名
  • ☐ 參數非空、非空字符串校驗
  • ☐ MyBatis <collection> 的 ofType、列名別名正確
  • ☐ SQL 使用 LEFT JOIN 保證公寓無教師時仍返回主記錄

遵循「參數驗證 → 映射配置 → SQL 驗證」三步走,徹底解決 1對多關聯查詢痛點。

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