MyBatis启动报错——无法解析java.util.List<java.lang.Integer>的问题分析
MyBatis启动报错——无法解析java.util.List<java.lang.Integer>的问题分析
1. 问题环境
- 项目技术标签:Spring Boot + MyBatis
- 报错地点:实例化
empController
时报错 - 引发原因:Mapper XML 文件
EmpMapper.xml
中的parameterType
写法不正确
2. 实际报错信息
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'empController':
Unsatisfied dependency expressed through field 'empService':
Error creating bean with name 'empServiceImpl':
Unsatisfied dependency expressed through field 'empMapper':
Error creating bean with name 'empMapper':
Error parsing Mapper XML.
The XML location is 'com/example/mapper/EmpMapper.xml'.
Cause: Error resolving class.
Cause: Could not resolve type alias 'java.util.List<java.lang.Integer>'.
Cause: java.lang.ClassNotFoundException: Cannot find class: java.util.List<java.lang.Integer>
3. 问题分析
- 原因:MyBatis 无法识别含有泛型的 Java 类名,如
java.util.List<java.lang.Integer>
- MyBatis 仅支持写 简单类名(比如 Integer,String,List),而不能直接写含有
<>
的泛型 - 将泛型直接写入 XML 会导致解析时报错
4. 原始代码
EmpMapper.xml:
<delete id="deleteEmp" parameterType="java.util.List<java.lang.Integer>">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
EmpMapper.java:
void deleteEmp(List<Integer> ids);
5. 正确修改方案
步骤 1:XML删除 parameterType
<delete id="deleteEmp">
delete from emp where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
步骤 2:接口方法加 @Param
void deleteEmp(@Param("ids") List<Integer> ids);
解释:
@Param("ids")
指定 XML 中<foreach collection="ids">
的 ids- MyBatis 通过此符合方法参数和 XML 里变量名定义
6. 总结分析
错误写法 | 正确写法 |
---|---|
parameterType="java.util.List<java.lang.Integer>" | 直接不写 parameterType |
void deleteEmp(List<Integer> ids); | void deleteEmp(@Param("ids") List<Integer> ids); |
根本原因:MyBatis XML 不支持泛型。
7. 小结
在 MyBatis XML 中,无论是parameterType
、resultType
,都 不能写泛型 (如List<Integer>
) ,只能写 单纯类名(如Integer
、List
);如果是集合、多参数,需通过@Param
指定名称。
文章作者: 无念log
文章链接: https://silys.nianlink.top/index.php/archives/114/
版权声明: 本网站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 伤极无念log-科技、爱好、工具!
文章链接: https://silys.nianlink.top/index.php/archives/114/
版权声明: 本网站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 伤极无念log-科技、爱好、工具!
评论