mybatis 的 Mapper 中的方法不能重载
前言
Mapper
接口的时候都重载过其中的方法,但是运行起来总是报错(注:在 mybatis-plus 里面不会报错,但是会使用第一个)。
环境配置
- 内容都是基于 mybatis3.5(mybatis-plus3.5.1)
和
SpringBoot-2.3.3.RELEASE`。
问题示范
- 有这样的一个 Mapper,一个是根据用户的id筛选用户,一个是根据用户的性别筛选,此时在 Mapper 中重载的方法如下:
public interface UserMapper {
List<UserInfo> selectList(@Param("userIds") List<String> userIds);
List<UserInfo> selectList(Integer gender);
}
- 在 mybatis 中但是启动项目,报出如下的错误:
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 collection already contains value for cn.cb.demo.dao.UserMapper.selectList. please check file [H:\work_project\demo\target\classes\mapper\UserInfoMapper.xml] and file [H:\work_project\demo\target\classes\mapper\UserInfoMapper.xml]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1509)
... 81 more
- 报错含义
cn.cb.demo.dao.UserMapper.selectList
这个id
已经存在了,导致创建sqlSessionFactory
失败。 - 在 mybatis-plus 中不会报错,但是调用方法的时候回去使用第一个(selectList(@Param("userIds") List<String> userIds))
mybatis 为什么不能重载?
- 通过上面的异常提示可以知道创建
sqlSessionFactory
失败了,这个想必已经不陌生吧,顾名思义,就是创建SqlSession
的工厂。 - Springboot 与 mybatis 会有一个启动器的自动配置类
MybatisAutoConfiguration
,其中有一段代码就是创建sqlSessionFactory
- 既然是创建失败,那么肯定是这里出现异常了,这里的 「大致思路」 就是:
解析
XML
文件和Mapper
接口,将 Mapper 中的方法与 XML 文件中<select>
、<insert>
等标签一一对应,那么 Mapper 中的方法如何与 XML 中<select>
这些标签对应了,当然是唯一的id
对应了。
![[Pasted image 20241202110426.png]]
- 如上图的
SqlSessionFactory
的创建过程中,前面的部分代码都是设置一些配置,并没有涉及到解析 XML 的内容,因此答案肯定是在最后一行return factory.getObject();
,于是此处打上断点,一点点看。于是一直到了org.mybatis.spring.SqlSessionFactoryBean#buildSqlSessionFactory
这个方法中,其中一段代码如下:
![[Pasted image 20241202110330.png]] - 这里的
xmlMapperBuilder.parse();
就是解析 XML 文件与 Mapper 接口,继续向下看。 - 略过不重要的代码,在
org.apache.ibatis.builder.xml.XMLMapperBuilder#configurationElement
这个方法中有一行重要的代码,如下图:
![[Pasted image 20241202110300.png]] - 此处就是根据 XML 文件中的
select|insert|update|delete
这些标签开始构建MappedStatement
了。继续跟进去看。 - 略过不重要的代码,此时看到
org.apache.ibatis.builder.MapperBuilderAssistant#addMappedStatement
这个方法返回值就是MappedStatement
,不用多说,肯定是这个方法了,仔细一看,很清楚的看到了构建id
的代码,如下图:
![[Pasted image 20241202110724.png]] - 从上图可以知道,创建
id
的代码就是id = applyCurrentNamespace(id, false);
,具体实现如下图:
![[Pasted image 20241202111014.png]]
上图的代码已经很清楚了,
MappedStatement
中的id = Mapper 的全类名+'.'+方法名
。如果重载话,肯定会存在id
相同的MappedStatement
。
- 到了这其实并不能说明方法不能重载啊,重复就重复呗,并没有冲突啊。这里需要看一个结构,如下:
![[Pasted image 20241202111906.png]]
protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
.conflictMessageProducer((savedValue, targetValue) ->
". please check " + savedValue.getResource() + " and " + targetValue.getResource());
- 构建好的
MappedStatement
都会存入mappedStatements
中,如下代码:
public void addMappedStatement(MappedStatement ms) {
//key 是 id
mappedStatements.put(ms.getId(), ms);
}
StrictMap
的put(k,v)
方法如下图:
![[Pasted image 20241202112013.png]]
抛出的异常和上面的
异常信息
对应起来了。这个StrictMap
不允许有重复的key
,而存入的key
就是id
。因此 Mapper 中的方法不能重载。
mybatis-plus 为什么不能重载?
进入 mapper 方法!这里直接进到 com.baomidou.mybatisplus.core.override.MybatisMapperProxy#invoke
![[Pasted image 20241202112810.png]]
这里都是 mybatis-plus 的代理。
进入跟进,进入到 com.baomidou.mybatisplus.core.override.MybatisMapperMethod#execute
![[Pasted image 20241202112824.png]]
这里相当于执行
Object result = sqlSession.selectOne("com.demo.mapper.xxxxMapper.xxxx", param);
![[Pasted image 20241202112850.png]]
在这里会进入 Mybatis 的 slectList 方法(org.apache.ibatis.session.defaults.DefaultSqlSession#selectList
)。
![[Pasted image 20241202112857.png]]
从 configuration
中生成所有的 mappedStatements,然后从 statements 中获取根据 id,也就是方法的全路径,获取当前的 statements。
![[Pasted image 20241202112904.png]]
- mappedStatements 是一个 Map 结构!
- 其中 key 是方法名,value 是一个 MappedStatement
所以这里的意思是根据方法的全路径名称,获取一个 MappedStatement, 而com.demo.mapper.xxxxMapper.xxxx
在这里面只有一个。
究其原因,则是因为 configuration 中就没有重载方法的 MappedStatement
而根本原因则是在 com.baomidou.mybatisplus.core.MybatisConfiguration#addMappedStatement 中写了一段代码!
![[Pasted image 20241202113033.png]]
如果已经存在,则直接忽略,同时会打印日志。
mapper[xxx] is ignored, because it exists, maybe from xml file
如何找到 XML 中对应的 SQL?
- 在使用 Mybatis 的时候只是简单的调用 Mapper 中的方法就可以执行 SQL,如下代码:
List<UserInfo> userInfos = userMapper.selectList(Arrays.asList("192","198"));
一行简单的调用到底如何找到对应的SQL呢?其实就是根据
id
从Map<String, MappedStatement> mappedStatements
中查找对应的MappedStatement
。
- 在
org.apache.ibatis.session.defaults.DefaultSqlSession#selectList
方法有这一行代码如下图:
![[Pasted image 20241202112350.png]] MappedStatement ms = configuration.getMappedStatement(statement);
这行代码就是根据id
从mappedStatements
获取对应的MappedStatement
,源码如下:
public MappedStatement getMappedStatement(String id) {
return this.getMappedStatement(id, true);
}
总结
- 就是因为这个这个
id=Mapper的全类名+'.'+方法名
,导致不能重载。 - 在 mybatis 中如果 MappedStatement 如果 key 存在,则直接抛出异常:java.lang.IllegalArgumentException: Mapped Statements collection already contains value xxx。
服务启动失败。 - 在 mybatis-plus 中 Mapper 重载并不会出现异常(发现该 MappedStatement 已经存在,则不进行添加),但是查询结果都是相同的。因为 mybatis-plus 的 MybatisConfiguration 继承重写了 MyBatisConfiguration 的 addMappedStatement 方法。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)