Mybatis3源码分析(20)-Mapper实现-配置加载

本文深入分析Mybatis3中Mapper接口的配置加载过程,探讨通过mybatis-config.xml的包(package)和class方法加载Mapper接口,并详细讲解MapperAnnotationBuilder.parse()方法的作用。在解析过程中,Mybatis读取注解生成MappedStatement对象,如果接口方法没有Select、Insert等八大注解之一,执行时将报MappedStatement找不到。同时,文章还介绍了MapperProxyFactory的生成及其在Mapper接口实例化中的作用。
摘要由CSDN通过智能技术生成

整体加载过程

  1. mybatis-config.xml中可以在包(package)和class的方法让Mybatis加载一个Mapper
  2. 通过包的方式是从包加载所有的class,最条还是通过class方法来实现加载
  3. 加载过程中主要通过读取方法中的注解来生成MappedStatement对象,再加入到Configuration中。这个过程跟解析mapper.xml配置文件中的select/insert/update/delete节点的过程差不多。一个是从xml里读取信息,一个是从注解里读取信息。
  4. 通过注解生成的MappedStatement的Id生成规则为接口全限定名名加方法的名字,所以在定义Mapper接口类时千万不要重载方法,否则会发生预想不到的问题。
  5. Mapper接口中的只有包含如下八种注解中的一种才会被Mybatis解析成一个MappedStatement对象。
    1. Select/Insert/Update/Delete
    2. SelectProvider/InsertProvider/UpdateProvider/DeleteProvider
    一个方法如果没有这些注解中的其中一个,执行时Mybatis会报MappedStatement找不到
  6. Mybatis加载一个Mapper接口时会为其生成一个MapperProxyFactory对象,由这个对象来创建Mapper接口的实例。MapperProxyFactory这个类的实现在下一节详细分析。

Mapper的配置加载是从XmlConfigBuilder.mapperElement()方法中触发的

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        
        if ("package".equals(child.getName())) {
          //通过package的方法
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configurat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值