前言
-
在初入门
Mybatis
的时候可能都犯过一个错误,那就是在写Mapper
接口的时候都重载过其中的方法,但是运行起来总是报错,那时候真的挺郁闷的,但是自己也查不出来原因,只能默默的改了方法名,哈哈,多么卑微的操作。 -
今天就写一篇文章从源码角度为大家解惑为什么
Mybatis
中的方法不能重载?
环境配置
-
本篇文章讲的一切内容都是基于
Mybatis3.5
和SpringBoot-2.3.3.RELEASE
。
错误示范
-
举个栗子:假设现在有两个需求,一个是根据用户的id筛选用户,一个是根据用户的性别筛选,此时在Mapper中重载的方法如下:
public interface UserMapper {
List<UserInfo> selectList(@Param("userIds") List<String> userIds);
List<UserInfo> selectList(Integer gender);
}
-
这个并没有什么错误,但是启动项目,报出如下的错误:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [H:\work_project\demo\target\classes\mapper\UserInfoMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [H:\work_project\demo\target\classes\mapper\UserInfoMapper.xml]'. Cause: java.lang.IllegalArgumentException: Mapped Statements collect