Action 中 Integer.parseInt(request.getParameter("ftId")) 拋出 NumberFormatException: null,導致教師公寓關聯查詢失敗。
apartmentId)與後端 getParameter("ftId") 不一致,取得 null。null 字符串導致異常。<collection>,導致關聯集合為空。String ftIdStr = ServletActionContext.getRequest().getParameter("ftId");
if (ftIdStr == null || ftIdStr.trim().isEmpty()) {
// 返回錯誤提示或預設值
return;
}
int ftId = Integer.parseInt(ftIdStr);
<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>
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();
}
}
getParameter 名<collection> 的 ofType、列名別名正確LEFT JOIN 保證公寓無教師時仍返回主記錄遵循「參數驗證 → 映射配置 → SQL 驗證」三步走,徹底解決 1對多關聯查詢痛點。