前言
-
在初入门
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 'sqlSessionF

本文从二进制角度解释了Mybatis中Mapper接口的方法不能重载的原因。当尝试重载方法时,会导致工厂创建失败,因为Mybatis在启动时会解析XML与Mapper接口,通过唯一标识建立对应关系。解析过程涉及反射和Map存储,Map不允许键的重复,因此Mapper方法不能重载。此外,执行SQL时,Mybatis根据方法签名从映射信息中找到对应的SQL。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



