Erlo

mybatis 的 Mapper 中的方法不能重载

2025-01-16 15:29:24 发布   24 浏览  
页面报错/反馈
收藏 点赞

前言

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

环境配置

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

问题示范

  • 有这样的一个 Mapper,一个是根据用户的id筛选用户,一个是根据用户的性别筛选,此时在 Mapper 中重载的方法如下:
public interface UserMapper {
    List selectList(@Param("userIds") List userIds);
 
    List 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_projectdemotargetclassesmapperUserInfoMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [H:work_projectdemotargetclassesmapperUserInfoMapper.xml]'. Cause: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for cn.cb.demo.dao.UserMapper.selectList. please check file [H:work_projectdemotargetclassesmapperUserInfoMapper.xml] and file [H:work_projectdemotargetclassesmapperUserInfoMapper.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 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]]
protected final Map mappedStatements = new StrictMap("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);
  }
  • StrictMapput(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]]

  1. mappedStatements 是一个 Map 结构!
  2. 其中 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 userInfos = userMapper.selectList(Arrays.asList("192","198"));

一行简单的调用到底如何找到对应的SQL呢?其实就是根据idMap mappedStatements中查找对应的MappedStatement

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

总结

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

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认