mybatis xml返回对象类型和接口定义类型不一致 📅 2026/8/14 5:29:44 问题背景最近在开发中发现MyBatis XML 映射文件中定义的返回值类型与 Mapper 接口中声明的泛型类型不一致导致实际查询返回的对象类型与预期不符。代码示例1. XML 映射文件 (xxxxMapper.xml)select idselectPlanList parameterTypePlan resultMapPlanListVo select * from table_name /selectresultMap typecom.demo.vo.PlanListVo idPlanListVo !-- 字段映射配置 -- id propertyid columnid/ result propertyname columnname/ result propertycreateTime columncreate_time/ /resultMap2. Mapper 接口 (xxxxMapper.java)ListPlan selectPlanList(Plan plan);3. Service 实现类 (xxxxServiceImpl.java)Override public ListPlan selectPlanList(Plan plan) { return planMapper.selectPlanList(plan); }问题分析在上述代码中XML 映射文件的resultMap指定返回类型为com.demo.vo.PlanListVo而 Mapper 接口中声明的返回类型为ListPlan。当调用planMapper.selectPlanList(plan)时MyBatis 会按照 XML 中配置的PlanListVo类型来创建对象并封装结果集。但由于 Java 泛型在运行时会被擦除接口中声明的ListPlan类型约束在运行时无法生效因此实际返回的是ListPlanListVo类型的列表而不是ListPlan。解决方案保持类型一致将 XML 中的resultMap类型改为Plan或者将 Mapper 接口的返回类型改为ListPlanListVo。使用类型别名在 MyBatis 配置文件中配置类型别名避免硬编码全限定类名。运行时类型检查在 Service 层对返回结果进行类型转换或验证确保类型安全。总结MyBatis 执行查询时实际返回的对象类型由 XML 映射文件中的resultType或resultMap决定而不是由 Mapper 接口的泛型声明决定。开发时需确保两者类型一致避免因泛型擦除导致的类型不匹配问题。