mybatis 的 Mapper 中的方法不能重载

宁睿  金牌会员 | 2025-1-16 15:22:26 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 942|帖子 942|积分 2836

目录

前言


  • Mapper接口的时候都重载过其中的方法,但是运行起来总是报错(注:在 mybatis-plus 里面不会报错,但是会使用第一个)。
环境设置


  • 内容都是基于 mybatis3.5(mybatis-plus3.5.1)和SpringBoot-2.3.3.RELEASE`。
问题示范


  • 有这样的一个 Mapper,一个是根据用户的id筛选用户,一个是根据用户的性别筛选,此时在 Mapper 中重载的方法如下:
  1. public interface UserMapper {
  2.     List<UserInfo> selectList(@Param("userIds") List<String> userIds);
  3.     List<UserInfo> selectList(Integer gender);
  4.     }
复制代码

  • 在 mybatis 中但是启动项目,报出如下的错误:
  1. 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]
  2. at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
  3. at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635)
  4. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
  5. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176)
  6. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556)
  7. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516)
  8. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324)
  9. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
  10. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322)
  11. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
  12. at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
  13. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307)
  14. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227)
  15. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1509)
  16. ... 81 more
复制代码

  • 报错含义 cn.cb.demo.dao.UserMapper.selectList 这个 id 已经存在了,导致创建 sqlSessionFactory 失败。
  • 在 mybatis-plus 中不会报错,但是调用方法的时候归去使用第一个(selectList(@Param("userIds") List userIds))
mybatis 为什么不能重载?


  • 通过上面的异常提示可以知道创建 sqlSessionFactory 失败了,这个想必已经不生疏吧,顾名思义,就是创建 SqlSession 的工厂。
  • Springboot 与 mybatis 会有一个启动器的自动设置类 MybatisAutoConfiguration,其中有一段代码就是创建 sqlSessionFactory
  • 既然是创建失败,那么肯定是这里出现异常了,这里的 「大抵思路」 就是:
解析 XML 文件和 Mapper 接口,将 Mapper 中的方法与 XML 文件中 、 等标签一一对应,那么 Mapper 中的方法如何与 XML 中  这些标签对应了,当然是唯一的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]]
  1. protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
  2.       .conflictMessageProducer((savedValue, targetValue) ->
  3.           ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
复制代码

  • 构建好的 MappedStatement 都会存入 mappedStatements 中,如下代码:
  1. public void addMappedStatement(MappedStatement ms) {
  2.     //key 是 id
  3.     mappedStatements.put(ms.getId(), ms);
  4.   }
复制代码

  • 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]]
这里相称于执行
  1. 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,如下代码:
  1. List<UserInfo> userInfos = userMapper.selectList(Arrays.asList("192","198"));
复制代码
一行简单的调用到底如何找到对应的SQL呢?其实就是根据id从Map mappedStatements中查找对应的MappedStatement。


  • 在org.apache.ibatis.session.defaults.DefaultSqlSession#selectList方法有这一行代码如下图:
    ![[Pasted image 20241202112350.png]]
  • MappedStatement ms = configuration.getMappedStatement(statement);这行代码就是根据 id 从 mappedStatements 获取对应的 MappedStatement,源码如下:
  1. public MappedStatement getMappedStatement(String id) {
  2.     return this.getMappedStatement(id, true);
  3. }
复制代码
总结


  • 就是因为这个这个id=Mapper的全类名+'.'+方法名,导致不能重载。
  • 在 mybatis 中如果 MappedStatement 如果 key 存在,则直接抛出异常:java.lang.IllegalArgumentException: Mapped Statements collection already contains value xxx。
    服务启动失败。
  • 在 mybatis-plus 中 Mapper 重载并不会出现异常(发现该 MappedStatement 已经存在,则不举行添加),但是查询结果都是相同的。因为 mybatis-plus 的 MybatisConfiguration 继承重写了 MyBatisConfiguration 的 addMappedStatement 方法。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

宁睿

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表