溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

發(fā)布時(shí)間:2021-10-28 16:18:51 來源:億速云 閱讀:172 作者:柒染 欄目:編程語言

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查,很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

一、前言介紹

MyBatis 是一款非常優(yōu)秀的持久層框架,相對于IBatis更是精進(jìn)了不少。與此同時(shí)它還提供了很多的擴(kuò)展點(diǎn),比如最常用的插件;語言驅(qū)動器,執(zhí)行器,對象工廠,對象包裝器工廠等等都可以擴(kuò)展。那么,如果想成為一個(gè)有深度的男人(程序猿),還是應(yīng)該好好的學(xué)習(xí)一下這款開源框架的源碼,以此可以更好的領(lǐng)會設(shè)計(jì)模式的精髓(面試?)。其實(shí)可能平常的業(yè)務(wù)開發(fā)中,并不會去深究各個(gè)框架的源代碼,也常常會聽到即使不會也可以開發(fā)代碼。但!每個(gè)人的目標(biāo)不同,就像;代碼寫的好工資加的少(沒有bug怎么看出你工作嘞!),好!為了改變世界,開始分析嘍!

在分析之前先出一個(gè)題,看看你適合看源碼不;

@Test  public void test(){      B b = new B();      b.scan();  //我的輸出結(jié)果是什么?  }  static class A {      public void scan(){          doScan();      }      protected void doScan(){          System.out.println("A.doScan");      }  } static class B extends A {      @Override      protected void doScan() {          System.out.println("B.doScan");      }  }

其實(shí)無論你的答案對錯,都不影響你對源碼的分析。只不過,往往在一些框架中會有很多的設(shè)計(jì)模式和開發(fā)技巧,如果上面的代碼在你平時(shí)的開發(fā)中幾乎沒用過,那么可能你暫時(shí)更多的還是開發(fā)著CRUD的功能(莫慌,我還寫過PHP呢)。

接下來先分析Mybatis單獨(dú)使用時(shí)的源碼執(zhí)行過程,再分析Mybatis+Spring整合源碼,好!開始。

二、案例工程

為了更好的分析,我們創(chuàng)建一個(gè)Mybaits的案例工程,其中包括;Mybatis單獨(dú)使用、Mybatis+Spring整合使用

itstack-demo-mybatis  └── src      ├── main      │   ├── java      │   │   └── org.itstack.demo      │   │       ├── dao      │   │       │    ├── ISchool.java        │   │       │    └── IUserDao.java         │   │       └── interfaces           │   │             ├── School.java        │   │            └── User.java      │   ├── resources          │   │   ├── mapper      │   │   │   ├── School_Mapper.xml      │   │   │   └── User_Mapper.xml      │   │   ├── props          │   │   │   └── jdbc.properties      │   │   ├── spring      │   │   │   ├── mybatis-config-datasource.xml      │   │   │   └── spring-config-datasource.xml      │   │   ├── logback.xml      │   │   ├── mybatis-config.xml      │   │   └── spring-config.xml      │   └── webapp      │       └── WEB-INF      └── test           └── java               └── org.itstack.demo.test                   ├── MybatisApiTest.java                   └── SpringApiTest.java

三、環(huán)境配置

  1.  JDK1.8

  2.  IDEA 2019.3.1

  3.  mybatis 3.4.6 {不同版本源碼略有差異和bug修復(fù)}

  4.  mybatis-spring 1.3.2 {以下源碼分析會說代碼行號,注意不同版本可能會有差異}

四、(mybatis)源碼分析

<dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis</artifactId>      <version>3.4.6</version>  </dependency>

Mybatis的整個(gè)源碼還是很大的,以下主要將部分核心內(nèi)容進(jìn)行整理分析,以便于后續(xù)分析Mybatis與Spring整合的源碼部分。簡要包括;容器初始化、配置文件解析、Mapper加載與動態(tài)代理。

1. 從一個(gè)簡單的案例開始

要學(xué)習(xí)Mybatis源碼,最好的方式一定是從一個(gè)簡單的點(diǎn)進(jìn)入,而不是從Spring整合開始分析。SqlSessionFactory是整個(gè)Mybatis的核心實(shí)例對象,SqlSessionFactory對象的實(shí)例又通過SqlSessionFactoryBuilder對象來獲得。SqlSessionFactoryBuilder對象可以從XML配置文件加載配置信息,然后創(chuàng)建SqlSessionFactory。如下例子:

MybatisApiTest.java

public class MybatisApiTest {      @Test      public void test_queryUserInfoById() {         String resource = "spring/mybatis-config-datasource.xml";          Reader reader;          try {              reader = Resources.getResourceAsReader(resource);              SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);              SqlSession session = sqlMapper.openSession();              try {                  User user = session.selectOne("org.itstack.demo.dao.IUserDao.queryUserInfoById", 1L);                  System.out.println(JSON.toJSONString(user));              } finally {                  session.close();                  reader.close();              }          } catch (IOException e) {              e.printStackTrace();          }      } }

dao/IUserDao.java

public interface IUserDao {       User queryUserInfoById(Long id);  }

spring/mybatis-config-datasource.xml

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"          "http://mybatis.org/dtd/mybatis-3-config.dtd">  <configuration>      <environments default="development">          <environment id="development">              <transactionManager type="JDBC"/>              <dataSource type="POOLED">                  <property name="driver" value="com.mysql.jdbc.Driver"/>                  <property name="url" value="jdbc:mysql://127.0.0.1:3306/itstack?useUnicode=true"/>                  <property name="username" value="root"/>                  <property name="password" value="123456"/>              </dataSource>          </environment>      </environments>      <mappers>          <mapper resource="mapper/User_Mapper.xml"/>      </mappers> </configuration>

如果一切順利,那么會有如下結(jié)果:

{"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}

從上面的代碼塊可以看到,核心代碼;SqlSessionFactoryBuilder().build(reader),負(fù)責(zé)Mybatis配置文件的加載、解析、構(gòu)建等職責(zé),直到最終可以通過SqlSession來執(zhí)行并返回結(jié)果。

2. 容器初始化

從上面代碼可以看到,SqlSessionFactory是通過SqlSessionFactoryBuilder工廠類創(chuàng)建的,而不是直接使用構(gòu)造器。容器的配置文件加載和初始化流程如下:

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

  •  流程核心類

    •   SqlSessionFactoryBuilder

    •   XMLConfigBuilder

    •   XPathParser

    •   Configuration

SqlSessionFactoryBuilder.java

public class SqlSessionFactoryBuilder {    public SqlSessionFactory build(Reader reader) {      return build(reader, null, null);    }    public SqlSessionFactory build(Reader reader, String environment) {      return build(reader, environment, null);    }    public SqlSessionFactory build(Reader reader, Properties properties) {      return build(reader, null, properties);    }    public SqlSessionFactory build(Reader reader, String environment, Properties properties) {      try {        XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);        return build(parser.parse());      } catch (Exception e) {        throw ExceptionFactory.wrapException("Error building SqlSession.", e);      } finally {        ErrorContext.instance().reset();        try {          reader.close();        } catch (IOException e) {          // Intentionally ignore. Prefer previous error.        }      }    }    public SqlSessionFactory build(InputStream inputStream) {      return build(inputStream, null, null);    }    public SqlSessionFactory build(InputStream inputStream, String environment) {      return build(inputStream, environment, null);    }    public SqlSessionFactory build(InputStream inputStream, Properties properties) {      return build(inputStream, null, properties);    }    public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {      try {        XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);        return build(parser.parse());      } catch (Exception e) {        throw ExceptionFactory.wrapException("Error building SqlSession.", e);      } finally {        ErrorContext.instance().reset();        try {          inputStream.close();        } catch (IOException e) {          // Intentionally ignore. Prefer previous error.        }      }    }    public SqlSessionFactory build(Configuration config) {      return new DefaultSqlSessionFactory(config);    }  }

從上面的源碼可以看到,SqlSessionFactory提供三種方式build構(gòu)建對象;

  •  字節(jié)流:java.io.InputStream

  •  字符流:java.io.Reader

  •  配置類:org.apache.ibatis.session.Configuration

那么,字節(jié)流、字符流都會創(chuàng)建配置文件解析類:XMLConfigBuilder,并通過parser.parse()生成Configuration,最后調(diào)用配置類構(gòu)建方法生成SqlSessionFactory。

XMLConfigBuilder.java

public class XMLConfigBuilder extends BaseBuilder {    private boolean parsed;    private final XPathParser parser;    private String environment;    private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();    ...    public XMLConfigBuilder(Reader reader, String environment, Properties props) {      this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);    }    ...  }
  1.  XMLConfigBuilder對于XML文件的加載和解析都委托于XPathParser,最終使用JDK自帶的javax.xml進(jìn)行XML解析(XPath)

  2.  XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver)

        1.  reader:使用字符流創(chuàng)建新的輸入源,用于對XML文件的讀取

        2.  validation:是否進(jìn)行DTD校驗(yàn)

        3.  variables:屬性配置信息

        4.  entityResolver:Mybatis硬編碼了new XMLMapperEntityResolver()提供XML默認(rèn)解析器

XMLMapperEntityResolver.java

public class XMLMapperEntityResolver implements EntityResolver {    private static final String IBATIS_CONFIG_SYSTEM = "ibatis-3-config.dtd";    private static final String IBATIS_MAPPER_SYSTEM = "ibatis-3-mapper.dtd";    private static final String MYBATIS_CONFIG_SYSTEM = "mybatis-3-config.dtd";    private static final String MYBATIS_MAPPER_SYSTEM = "mybatis-3-mapper.dtd";    private static final String MYBATIS_CONFIG_DTD = "org/apache/ibatis/builder/xml/mybatis-3-config.dtd";    private static final String MYBATIS_MAPPER_DTD = "org/apache/ibatis/builder/xml/mybatis-3-mapper.dtd";    /*    * Converts a public DTD into a local one     *      * @param publicId The public id that is what comes after "PUBLIC"     * @param systemId The system id that is what comes after the public id.     * @return The InputSource for the DTD     *      * @throws org.xml.sax.SAXException If anything goes wrong     */    @Override    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {      try {        if (systemId != null) {          String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);          if (lowerCaseSystemId.contains(MYBATIS_CONFIG_SYSTEM) || lowerCaseSystemId.contains(IBATIS_CONFIG_SYSTEM)) {            return getInputSource(MYBATIS_CONFIG_DTD, publicId, systemId);          } else if (lowerCaseSystemId.contains(MYBATIS_MAPPER_SYSTEM) || lowerCaseSystemId.contains(IBATIS_MAPPER_SYSTEM)) {            return getInputSource(MYBATIS_MAPPER_DTD, publicId, systemId);          }        }        return null;      } catch (Exception e) {        throw new SAXException(e.toString());      }    }    private InputSource getInputSource(String path, String publicId, String systemId) {      InputSource source = null;      if (path != null) {        try {          InputStream in = Resources.getResourceAsStream(path);          source = new InputSource(in);          source.setPublicId(publicId);          source.setSystemId(systemId);                } catch (IOException e) {          // ignore, null is ok        }      }      return source;    }  }
  1.  Mybatis依賴于dtd文件進(jìn)行進(jìn)行解析,其中的ibatis-3-config.dtd主要是用于兼容用途

  2.  getInputSource(String path, String publicId, String systemId)的調(diào)用里面有兩個(gè)參數(shù)publicId(公共標(biāo)識符)和systemId(系統(tǒng)標(biāo)示符)

XPathParser.java

public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) {    commonConstructor(validation, variables, entityResolver);    this.document = createDocument(new InputSource(reader));  }  private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) {    this.validation = validation;    this.entityResolver = entityResolver;    this.variables = variables;    XPathFactory factory = XPathFactory.newInstance();    this.xpath = factory.newXPath();  }  private Document createDocument(InputSource inputSource) {    // important: this must only be called AFTER common constructor    try {      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();      factory.setValidating(validation);      factory.setNamespaceAware(false);      factory.setIgnoringComments(true);      factory.setIgnoringElementContentWhitespace(false);      factory.setCoalescing(false);      factory.setExpandEntityReferences(true);      DocumentBuilder builder = factory.newDocumentBuilder();      builder.setEntityResolver(entityResolver);      builder.setErrorHandler(new ErrorHandler() {        @Override        public void error(SAXParseException exception) throws SAXException {          throw exception;        }        @Override        public void fatalError(SAXParseException exception) throws SAXException {          throw exception;        }        @Override        public void warning(SAXParseException exception) throws SAXException {        }      });      return builder.parse(inputSource);    } catch (Exception e) {      throw new BuilderException("Error creating document instance.  Cause: " + e, e);   }  }
  1.  從上到下可以看到主要是為了創(chuàng)建一個(gè)Mybatis的文檔解析器,最后根據(jù)builder.parse(inputSource)返回Document

  2.  得到XPathParser實(shí)例后,接下來在調(diào)用方法:this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);   

XMLConfigBuilder.this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);      private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {        super(new Configuration());        ErrorContext.instance().resource("SQL Mapper Configuration");        this.configuration.setVariables(props);        this.parsed = false;        this.environment = environment;        this.parser = parser;      }

    3.  其中調(diào)用了父類的構(gòu)造函數(shù) 

public abstract class BaseBuilder {        protected final Configuration configuration;        protected final TypeAliasRegistry typeAliasRegistry;        protected final TypeHandlerRegistry typeHandlerRegistry;       public BaseBuilder(Configuration configuration) {          this.configuration = configuration;          thisthis.typeAliasRegistry = this.configuration.getTypeAliasRegistry();          thisthis.typeHandlerRegistry = this.configuration.getTypeHandlerRegistry();        }      }

    4.  XMLConfigBuilder創(chuàng)建完成后,sqlSessionFactoryBuild調(diào)用parser.parse()創(chuàng)建Configuration

public class XMLConfigBuilder extends BaseBuilder {           public Configuration parse() {         if (parsed) {          throw new BuilderException("Each XMLConfigBuilder can only be used once.");         }         parsed = true;         parseConfiguration(parser.evalNode("/configuration"));         return configuration;       }  }

3. 配置文件解析

這一部分是整個(gè)XML文件解析和裝載的核心內(nèi)容,其中包括;

  1.  屬性解析propertiesElement

  2.  加載settings節(jié)點(diǎn)settingsAsProperties

  3.  載自定義VFS loadCustomVfs

  4.  解析類型別名typeAliasesElement

  5.  加載插件pluginElement

  6.  加載對象工廠objectFactoryElement

  7.  創(chuàng)建對象包裝器工廠objectWrapperFactoryElement

  8.  加載反射工廠reflectorFactoryElement

  9.  元素設(shè)置settingsElement

  10.  加載環(huán)境配置environmentsElement

  11.  數(shù)據(jù)庫廠商標(biāo)識加載databaseIdProviderElement

  12.  加載類型處理器typeHandlerElement

  13.  (核心)加載mapper文件mapperElement 

parseConfiguration(parser.evalNode("/configuration"));  private void parseConfiguration(XNode root) {      try {        //issue #117 read properties first        //屬性解析propertiesElement        propertiesElement(root.evalNode("properties"));        //加載settings節(jié)點(diǎn)settingsAsProperties        Properties settings = settingsAsProperties(root.evalNode("settings"));        //加載自定義VFS loadCustomVfs        loadCustomVfs(settings);        //解析類型別名typeAliasesElement        typeAliasesElement(root.evalNode("typeAliases"));        //加載插件pluginElement        pluginElement(root.evalNode("plugins"));        //加載對象工廠objectFactoryElement        objectFactoryElement(root.evalNode("objectFactory"));        //創(chuàng)建對象包裝器工廠objectWrapperFactoryElement        objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));        //加載反射工廠reflectorFactoryElement        reflectorFactoryElement(root.evalNode("reflectorFactory"));        //元素設(shè)置        settingsElement(settings);        // read it after objectFactory and objectWrapperFactory issue #631        //加載環(huán)境配置environmentsElement        environmentsElement(root.evalNode("environments"));        //數(shù)據(jù)庫廠商標(biāo)識加載databaseIdProviderElement        databaseIdProviderElement(root.evalNode("databaseIdProvider"));        //加載類型處理器typeHandlerElement        typeHandlerElement(root.evalNode("typeHandlers"));        //加載mapper文件mapperElement        mapperElement(root.evalNode("mappers"));      } catch (Exception e) {        throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);      }  }

所有的root.evalNode()底層都是調(diào)用XML DOM方法:Object evaluate(String expression, Object item, QName returnType),表達(dá)式參數(shù)expression,通過XObject resultObject = eval( expression, item )返回最終節(jié)點(diǎn)內(nèi)容,可以參考http://mybatis.org/dtd/mybati...,如下;

<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)> <!ELEMENT databaseIdProvider (property*)>  <!ATTLIST databaseIdProvider  type CDATA #REQUIRED  >  <!ELEMENT properties (property*)>  <!ATTLIST properties  resource CDATA #IMPLIED  url CDATA #IMPLIED  >  <!ELEMENT property EMPTY>  <!ATTLIST property  name CDATA #REQUIRED  value CDATA #REQUIRED  > <!ELEMENT settings (setting+)>  <!ELEMENT setting EMPTY>  <!ATTLIST setting  name CDATA #REQUIRED  value CDATA #REQUIRED  >  <!ELEMENT typeAliases (typeAlias*,package*)> <!ELEMENT typeAlias EMPTY>  <!ATTLIST typeAlias  type CDATA #REQUIRED  alias CDATA #IMPLIED  >  <!ELEMENT typeHandlers (typeHandler*,package*)>  <!ELEMENT typeHandler EMPTY>  <!ATTLIST typeHandler  javaType CDATA #IMPLIED  jdbcType CDATA #IMPLIED  handler CDATA #REQUIRED  > <!ELEMENT objectFactory (property*)>  <!ATTLIST objectFactory  type CDATA #REQUIRED  >  <!ELEMENT objectWrapperFactory EMPTY>  <!ATTLIST objectWrapperFactory  type CDATA #REQUIRED  >  <!ELEMENT reflectorFactory EMPTY>  <!ATTLIST reflectorFactory  type CDATA #REQUIRED  > <!ELEMENT plugins (plugin+)>  <!ELEMENT plugin (property*)> <!ATTLIST plugin  interceptor CDATA #REQUIRED  >  <!ELEMENT environments (environment+)>  <!ATTLIST environments  default CDATA #REQUIRED  >  <!ELEMENT environment (transactionManager,dataSource)>  <!ATTLIST environment  id CDATA #REQUIRED  >  <!ELEMENT transactionManager (property*)>  <!ATTLIST transactionManager  type CDATA #REQUIRED  >  <!ELEMENT dataSource (property*)>  <!ATTLIST dataSource  type CDATA #REQUIRED  >  <!ELEMENT mappers (mapper*,package*)>  <!ELEMENT mapper EMPTY>  <!ATTLIST mapper  resource CDATA #IMPLIED  url CDATA #IMPLIED  class CDATA #IMPLIED  >  <!ELEMENT package EMPTY>  <!ATTLIST package  name CDATA #REQUIRED  >

mybatis-3-config.dtd 定義文件中有11個(gè)配置文件,如下;

  1.  properties?,

  2.  settings?,

  3.  typeAliases?,

  4.  typeHandlers?,

  5.  objectFactory?,

  6.  objectWrapperFactory?,

  7.  reflectorFactory?,

  8.  plugins?,

  9.  environments?,

  10.  databaseIdProvider?,

  11.  mappers?

以上每個(gè)配置都是可選。最終配置內(nèi)容會保存到org.apache.ibatis.session.Configuration,如下;

public class Configuration {    protected Environment environment;    // 允許在嵌套語句中使用分頁(RowBounds)。如果允許使用則設(shè)置為false。默認(rèn)為false    protected boolean safeRowBoundsEnabled;    // 允許在嵌套語句中使用分頁(ResultHandler)。如果允許使用則設(shè)置為false。   protected boolean safeResultHandlerEnabled = true;    // 是否開啟自動駝峰命名規(guī)則(camel case)映射,即從經(jīng)典數(shù)據(jù)庫列名 A_COLUMN 到經(jīng)典 Java 屬性名 aColumn 的類似映射。默認(rèn)false    protected boolean mapUnderscoreToCamelCase;    // 當(dāng)開啟時(shí),任何方法的調(diào)用都會加載該對象的所有屬性。否則,每個(gè)屬性會按需加載。默認(rèn)值false (true in &le;3.4.1)    protected boolean aggressiveLazyLoading;    // 是否允許單一語句返回多結(jié)果集(需要兼容驅(qū)動)。    protected boolean multipleResultSetsEnabled = true;    // 允許 JDBC 支持自動生成主鍵,需要驅(qū)動兼容。這就是insert時(shí)獲取mysql自增主鍵/oracle sequence的開關(guān)。注:一般來說,這是希望的結(jié)果,應(yīng)該默認(rèn)值為true比較合適。    protected boolean useGeneratedKeys;    // 使用列標(biāo)簽代替列名,一般來說,這是希望的結(jié)果    protected boolean useColumnLabel = true;    // 是否啟用緩存 {默認(rèn)是開啟的,可能這也是你的面試題}    protected boolean cacheEnabled = true;    // 指定當(dāng)結(jié)果集中值為 null 的時(shí)候是否調(diào)用映射對象的 setter(map 對象時(shí)為 put)方法,這對于有 Map.keySet() 依賴或 null 值初始化的時(shí)候是有用的。    protected boolean callSettersOnNulls;    // 允許使用方法簽名中的名稱作為語句參數(shù)名稱。 為了使用該特性,你的工程必須采用Java 8編譯,并且加上-parameters選項(xiàng)。(從3.4.1開始)    protected boolean useActualParamName = true;    //當(dāng)返回行的所有列都是空時(shí),MyBatis默認(rèn)返回null。 當(dāng)開啟這個(gè)設(shè)置時(shí),MyBatis會返回一個(gè)空實(shí)例。 請注意,它也適用于嵌套的結(jié)果集 (i.e. collectioin and association)。(從3.4.2開始) 注:這里應(yīng)該拆分為兩個(gè)參數(shù)比較合適, 一個(gè)用于結(jié)果集,一個(gè)用于單記錄。通常來說,我們會希望結(jié)果集不是null,單記錄仍然是null    protected boolean returnInstanceForEmptyRow;    // 指定 MyBatis 增加到日志名稱的前綴。    protected String logPrefix;    // 指定 MyBatis 所用日志的具體實(shí)現(xiàn),未指定時(shí)將自動查找。一般建議指定為slf4j或log4j    protected Class <? extends Log> logImpl;     // 指定VFS的實(shí)現(xiàn), VFS是mybatis提供的用于訪問AS內(nèi)資源的一個(gè)簡便接口    protected Class <? extends VFS> vfsImpl;    // MyBatis 利用本地緩存機(jī)制(Local Cache)防止循環(huán)引用(circular references)和加速重復(fù)嵌套查詢。 默認(rèn)值為 SESSION,這種情況下會緩存一個(gè)會話中執(zhí)行的所有查詢。 若設(shè)置值為 STATEMENT,本地會話僅用在語句執(zhí)行上,對相同 SqlSession 的不同調(diào)用將不會共享數(shù)據(jù)。    protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;    // 當(dāng)沒有為參數(shù)提供特定的 JDBC 類型時(shí),為空值指定 JDBC 類型。 某些驅(qū)動需要指定列的 JDBC 類型,多數(shù)情況直接用一般類型即可,比如 NULL、VARCHAR 或 OTHER。    protected JdbcType jdbcTypeForNull = JdbcType.OTHER;    // 指定對象的哪個(gè)方法觸發(fā)一次延遲加載。    protected Set<String> lazyLoadTriggerMethods = new HashSet<String>(Arrays.asList(new String[] { "equals", "clone", "hashCode", "toString" }));    // 設(shè)置超時(shí)時(shí)間,它決定驅(qū)動等待數(shù)據(jù)庫響應(yīng)的秒數(shù)。默認(rèn)不超時(shí)    protected Integer defaultStatementTimeout;    // 為驅(qū)動的結(jié)果集設(shè)置默認(rèn)獲取數(shù)量。    protected Integer defaultFetchSize;    // SIMPLE 就是普通的執(zhí)行器;REUSE 執(zhí)行器會重用預(yù)處理語句(prepared statements); BATCH 執(zhí)行器將重用語句并執(zhí)行批量更新。    protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;    // 指定 MyBatis 應(yīng)如何自動映射列到字段或?qū)傩浴?nbsp;NONE 表示取消自動映射;PARTIAL 只會自動映射沒有定義嵌套結(jié)果集映射的結(jié)果集。 FULL 會自動映射任意復(fù)雜的結(jié)果集(無論是否嵌套)。    protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;    // 指定發(fā)現(xiàn)自動映射目標(biāo)未知列(或者未知屬性類型)的行為。這個(gè)值應(yīng)該設(shè)置為WARNING比較合適    protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;    // settings下的properties屬性    protected Properties variables = new Properties();    // 默認(rèn)的反射器工廠,用于操作屬性、構(gòu)造器方便    protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();    // 對象工廠, 所有的類resultMap類都需要依賴于對象工廠來實(shí)例化    protected ObjectFactory objectFactory = new DefaultObjectFactory();    // 對象包裝器工廠,主要用來在創(chuàng)建非原生對象,比如增加了某些監(jiān)控或者特殊屬性的代理類    protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();    // 延遲加載的全局開關(guān)。當(dāng)開啟時(shí),所有關(guān)聯(lián)對象都會延遲加載。特定關(guān)聯(lián)關(guān)系中可通過設(shè)置fetchType屬性來覆蓋該項(xiàng)的開關(guān)狀態(tài)。    protected boolean lazyLoadingEnabled = false;    // 指定 Mybatis 創(chuàng)建具有延遲加載能力的對象所用到的代理工具。MyBatis 3.3+使用JAVASSIST    protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL    // MyBatis 可以根據(jù)不同的數(shù)據(jù)庫廠商執(zhí)行不同的語句,這種多廠商的支持是基于映射語句中的 databaseId 屬性。    protected String databaseId;    ...  }

以上可以看到,Mybatis把所有的配置;resultMap、Sql語句、插件、緩存等都維護(hù)在Configuration中。這里還有一個(gè)小技巧,在Configuration還有一個(gè)StrictMap內(nèi)部類,它繼承于HashMap完善了put時(shí)防重、get時(shí)取不到值的異常處理,如下;

protected static class StrictMap<V> extends HashMap<String, V> {      private static final long serialVersionUID = -4950446264854982944L;      private final String name;      public StrictMap(String name, int initialCapacity, float loadFactor) {        super(initialCapacity, loadFactor);        this.name = name;      }      public StrictMap(String name, int initialCapacity) {        super(initialCapacity);        this.name = name;      }      public StrictMap(String name) {        super();        this.name = name;      }      public StrictMap(String name, Map<String, ? extends V> m) {        super(m);        this.name = name;      }  }

(核心)加載mapper文件mapperElement

Mapper文件處理是Mybatis框架的核心服務(wù),所有的SQL語句都編寫在Mapper中,這塊也是我們分析的重點(diǎn),其他模塊可以后續(xù)講解。

XMLConfigBuilder.parseConfiguration()->mapperElement(root.evalNode("mappers"));

private void mapperElement(XNode parent) throws Exception {     if (parent != null) {       for (XNode child : parent.getChildren()) {         // 如果要同時(shí)使用package自動掃描和通過mapper明確指定要加載的mapper,一定要確保package自動掃描的范圍不包含明確指定的mapper,否則在通過package掃描的interface的時(shí)候,嘗試加載對應(yīng)xml文件的loadXmlResource()的邏輯中出現(xiàn)判重出錯,報(bào)org.apache.ibatis.binding.BindingException異常,即使xml文件中包含的內(nèi)容和mapper接口中包含的語句不重復(fù)也會出錯,包括加載mapper接口時(shí)自動加載的xml mapper也一樣會出錯。         if ("package".equals(child.getName())) {           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, configuration.getSqlFragments());             mapperParser.parse();           } else if (resource == null && url == null && mapperClass != null) {             Class<?> mapperInterface = Resources.classForName(mapperClass);             configuration.addMapper(mapperInterface);           } else {             throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");           }         }       }     }  }
  •  Mybatis提供了兩類配置Mapper的方法,第一類是使用package自動搜索的模式,這樣指定package下所有接口都會被注冊為mapper,也是在Spring中比較常用的方式,例如:   

<mappers>       <package name="org.itstack.demo"/>     </mappers>
  •  另外一類是明確指定Mapper,這又可以通過resource、url或者class進(jìn)行細(xì)分,例如;   

<mappers>         <mapper resource="mapper/User_Mapper.xml"/>         <mapper class=""/>         <mapper url=""/>     </mappers>

4. Mapper加載與動態(tài)代理

通過package方式自動搜索加載,生成對應(yīng)的mapper代理類,代碼塊和流程,如下;

private void mapperElement(XNode parent) throws Exception {    if (parent != null) {      for (XNode child : parent.getChildren()) {        if ("package".equals(child.getName())) {          String mapperPackage = child.getStringAttribute("name");          configuration.addMappers(mapperPackage);        } else {          ...        }      }    }  }

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

Mapper加載到生成代理對象的流程中,主要的核心類包括;

  1.  XMLConfigBuilder

  2.  Configuration

  3.  MapperRegistry

  4.  MapperAnnotationBuilder

  5.  MapperProxyFactory

MapperRegistry.java

解析加載Mapper

public void addMappers(String packageName, Class<?> superType) {    // mybatis框架提供的搜索classpath下指定package以及子package中符合條件(注解或者繼承于某個(gè)類/接口)的類,默認(rèn)使用Thread.currentThread().getContextClassLoader()返回的加載器,和spring的工具類殊途同歸。    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();       // 無條件的加載所有的類,因?yàn)檎{(diào)用方傳遞了Object.class作為父類,這也給以后的指定mapper接口預(yù)留了余地    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);    // 所有匹配的calss都被存儲在ResolverUtil.matches字段中    Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();    for (Class<?> mapperClass : mapperSet) {         //調(diào)用addMapper方法進(jìn)行具體的mapper類/接口解析      addMapper(mapperClass);    }  }

生成代理類:MapperProxyFactory

public <T> void addMapper(Class<T> type) {        // 對于mybatis mapper接口文件,必須是interface,不能是class    if (type.isInterface()) {      if (hasMapper(type)) {        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");      }      boolean loadCompleted = false;      try {              // 為mapper接口創(chuàng)建一個(gè)MapperProxyFactory代理        knownMappers.put(type, new MapperProxyFactory<T>(type));        // It's important that the type is added before the parser is run        // otherwise the binding may automatically be attempted by the        // mapper parser. If the type is already known, it won't try.        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);        parser.parse();        loadCompleted = true;      } finally {        if (!loadCompleted) {          knownMappers.remove(type);        }      }    }  }

在MapperRegistry中維護(hù)了接口類與代理工程的映射關(guān)系,knownMappers;

private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();

MapperProxyFactory.java

public class MapperProxyFactory<T> {    private final Class<T> mapperInterface;    private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();    public MapperProxyFactory(Class<T> mapperInterface) {      this.mapperInterface = mapperInterface;    }    public Class<T> getMapperInterface() {      return mapperInterface;    }    public Map<Method, MapperMethod> getMethodCache() {      return methodCache;    }    @SuppressWarnings("unchecked")    protected T newInstance(MapperProxy<T> mapperProxy) {      return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);    }    public T newInstance(SqlSession sqlSession) {      final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);      return newInstance(mapperProxy);    }  }

如上是Mapper的代理類工程,構(gòu)造函數(shù)中的mapperInterface就是對應(yīng)的接口類,當(dāng)實(shí)例化時(shí)候會獲得具體的MapperProxy代理,里面主要包含了SqlSession。

五、(mybatis-spring)源碼分析

<dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis-spring</artifactId>      <version>1.3.2</version>  </dependency>

作為一款好用的ORM框架,一定是蘿莉臉(單純)、御姐心(強(qiáng)大),鋪的了床(屏蔽與JDBC直接打交道)、暖的了房(速度性能好)!鑒于這些優(yōu)點(diǎn)幾乎在國內(nèi)互聯(lián)網(wǎng)大部分開發(fā)框架都會使用到Mybatis,尤其在一些需要高性能的場景下需要優(yōu)化sql那么一定需要手寫sql在xml中。那么,準(zhǔn)備好了嗎!開始分析分析它的源碼;

1. 從一個(gè)簡單的案例開始

與分析mybatis源碼一樣,先做一個(gè)簡單的案例;定義dao、編寫配置文件、junit單元測試;

SpringApiTest.java

@RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration("classpath:spring-config.xml")  public class SpringApiTest {     private Logger logger = LoggerFactory.getLogger(SpringApiTest.class);      @Resource      private ISchoolDao schoolDao;      @Resource      private IUserDao userDao;      @Test      public void test_queryRuleTreeByTreeId(){          School ruleTree = schoolDao.querySchoolInfoById(1L);          logger.info(JSON.toJSONString(ruleTree));          User user = userDao.queryUserInfoById(1L);          logger.info(JSON.toJSONString(user));      }  }

spring-config-datasource.xml

<?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http://www.springframework.org/schema/beans"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans.xsd">     <!-- 1.數(shù)據(jù)庫連接池: DriverManagerDataSource 也可以使用DBCP2-->      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">          <property name="driverClassName" value="${db.jdbc.driverClassName}"/>          <property name="url" value="${db.jdbc.url}"/>          <property name="username" value="${db.jdbc.username}"/>          <property name="password" value="${db.jdbc.password}"/>      </bean>      <!-- 2.配置SqlSessionFactory對象 -->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <!-- 注入數(shù)據(jù)庫連接池 -->          <property name="dataSource" ref="dataSource"/>          <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->          <property name="configLocation" value="classpath:mybatis-config.xml"/>          <!-- 掃描entity包 使用別名 -->          <property name="typeAliasesPackage" value="org.itstack.demo.po"/>          <!-- 掃描sql配置文件:mapper需要的xml文件 -->          <property name="mapperLocations" value="classpath:mapper/*.xml"/>      </bean>      <!-- 3.配置掃描Dao接口包,動態(tài)實(shí)現(xiàn)Dao接口,注入到spring容器中 -->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <!-- 注入sqlSessionFactory -->          <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>          <!-- 給出需要掃描Dao接口包,多個(gè)逗號隔開 -->          <property name="basePackage" value="org.itstack.demo.dao"/>      </bean>            </beans>

如果一切順利,那么會有如下結(jié)果:

{"address":"北京市海淀區(qū)頤和園路5號","createTime":1571376957000,"id":1,"name":"北京大學(xué)","updateTime":1571376957000}  {"age":18,"createTime":1571376957000,"id":1,"name":"花花","updateTime":1571376957000}

從上面單元測試的代碼可以看到,兩個(gè)沒有方法體的注解就這么神奇的執(zhí)行了我們的xml中的配置語句并輸出了結(jié)果。其實(shí)主要得益于以下兩個(gè)類;

  •  org.mybatis.spring.SqlSessionFactoryBean

  •  org.mybatis.spring.mapper.MapperScannerConfigurer

2. 掃描裝配注冊(MapperScannerConfigurer)

MapperScannerConfigurer為整個(gè)Dao接口層生成動態(tài)代理類注冊,啟動到了核心作用。這個(gè)類實(shí)現(xiàn)了如下接口,用來對掃描的Mapper進(jìn)行處理:

  •  BeanDefinitionRegistryPostProcessor

  •  InitializingBean

  •  ApplicationContextAware

  •  BeanNameAware

整體類圖如下;

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

執(zhí)行流程如下;

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

上面的類圖+流程圖,其實(shí)已經(jīng)很清楚的描述了MapperScannerConfigurer初始化過程,但對于頭一次看的新人來說依舊是我太難了,好繼續(xù)!

MapperScannerConfigurer.java & 部分截取

@Override  public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {    if (this.processPropertyPlaceHolders) {      processPropertyPlaceHolders();    }    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);    scanner.setAddToConfig(this.addToConfig);    scanner.setAnnotationClass(this.annotationClass);    scanner.setMarkerInterface(this.markerInterface);    scanner.setSqlSessionFactory(this.sqlSessionFactory);    scanner.setSqlSessionTemplate(this.sqlSessionTemplate);    scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);    scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);    scanner.setResourceLoader(this.applicationContext);    scanner.setBeanNameGenerator(this.nameGenerator);    scanner.registerFilters();    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));  }
  •  實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry用于注冊Bean到Spring容器中

  •  306行:new ClassPathMapperScanner(registry); 硬編碼類路徑掃描器,用于解析Mybatis的Mapper文件

  •  317行:scanner.scan 對Mapper進(jìn)行掃描。這里包含了一個(gè)繼承類實(shí)現(xiàn)關(guān)系的調(diào)用,也就是本文開頭的測試題。

ClassPathMapperScanner.java & 部分截取

@Override  public Set<BeanDefinitionHolder> doScan(String... basePackages) {    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);    if (beanDefinitions.isEmpty()) {      logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");    } else {      processBeanDefinitions(beanDefinitions);    }    return beanDefinitions;  }
  •  優(yōu)先調(diào)用父類的super.doScan(basePackages);進(jìn)行注冊Bean信息

ClassPathBeanDefinitionScanner.java & 部分截取

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {      Assert.notEmpty(basePackages, "At least one base package must be specified");      Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();      for (String basePackage : basePackages) {          Set<BeanDefinition> candidates = findCandidateComponents(basePackage);          for (BeanDefinition candidate : candidates) {              ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);              candidate.setScope(scopeMetadata.getScopeName());              String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);              if (candidate instanceof AbstractBeanDefinition) {                  postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);              }              if (candidate instanceof AnnotatedBeanDefinition) {                  AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate)              }              if (checkCandidate(beanName, candidate)) {                  BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);                  definitionHolder =                          AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.regi                  beanDefinitions.add(definitionHolder);                  registerBeanDefinition(definitionHolder, this.registry);              }          }      }      return beanDefinitions;  }
  •  優(yōu)先調(diào)用了父類的doScan方法,用于Mapper掃描和Bean的定義以及注冊到DefaultListableBeanFactory。{DefaultListableBeanFactory是Spring中IOC容器的始祖,所有需要實(shí)例化的類都需要注冊進(jìn)來,之后在初始化}

  •  272行:findCandidateComponents(basePackage),掃描package包路徑,對于注解類的有另外的方式,大同小異

  •  288行:registerBeanDefinition(definitionHolder, this.registry);注冊Bean信息的過程,最終會調(diào)用到:org.springframework.beans.factory.support.DefaultListableBeanFactory

ClassPathMapperScanner.java & 部分截取

**processBeanDefinitions(beanDefinitions);**  private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {    GenericBeanDefinition definition;    for (BeanDefinitionHolder holder : beanDefinitions) {      definition = (GenericBeanDefinition) holder.getBeanDefinition();      if (logger.isDebugEnabled()) {        logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName()           + "' and '" + definition.getBeanClassName() + "' mapperInterface");      }      // the mapper interface is the original class of the bean      // but, the actual class of the bean is MapperFactoryBean      definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59      definition.setBeanClass(this.mapperFactoryBean.getClass());      definition.getPropertyValues().add("addToConfig", this.addToConfig);      boolean explicitFactoryUsed = false;      if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {        definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));        explicitFactoryUsed = true;      } else if (this.sqlSessionFactory != null) {        definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);        explicitFactoryUsed = true;      }      if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {        if (explicitFactoryUsed) {          logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");        }        definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));        explicitFactoryUsed = true;      } else if (this.sqlSessionTemplate != null) {        if (explicitFactoryUsed) {          logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");        }        definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);        explicitFactoryUsed = true;      }      if (!explicitFactoryUsed) {        if (logger.isDebugEnabled()) {          logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");        }        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);      }    }  }
  •  163行:super.doScan(basePackages);,調(diào)用完父類方法后開始執(zhí)行內(nèi)部方法:processBeanDefinitions(beanDefinitions)

  •  186行:definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); 設(shè)置BeanName參數(shù),也就是我們的:ISchoolDao、IUserDao

  •  187行:definition.setBeanClass(this.mapperFactoryBean.getClass());,設(shè)置BeanClass,接口本身是沒有類的,那么這里將MapperFactoryBean類設(shè)置進(jìn)來,最終所有的dao層接口類都是這個(gè)MapperFactoryBean

MapperFactoryBean.java & 部分截取

這個(gè)類有繼承也有接口實(shí)現(xiàn),最好先了解下整體類圖,如下;

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

這個(gè)類就非常重要了,最終所有的sql信息執(zhí)行都會通過這個(gè)類獲取getObject(),也就是SqlSession獲取mapper的代理類:MapperProxyFactory->MapperProxy

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {    private Class<T> mapperInterface;    private boolean addToConfig = true;    public MapperFactoryBean() {      //intentionally empty     }    public MapperFactoryBean(Class<T> mapperInterface) {      this.mapperInterface = mapperInterface;    }    /**       * 當(dāng)SpringBean容器初始化時(shí)候會調(diào)用到checkDaoConfig(),他是繼承類中的抽象方法     * {@inheritDoc}     */    @Override    protected void checkDaoConfig() {      super.checkDaoConfig();      notNull(this.mapperInterface, "Property 'mapperInterface' is required");     Configuration configuration = getSqlSession().getConfiguration();      if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {        try {          configuration.addMapper(this.mapperInterface);        } catch (Exception e) {          logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);          throw new IllegalArgumentException(e);        } finally {          ErrorContext.instance().reset();        }      }    }   /**     * {@inheritDoc}     */    @Override    public T getObject() throws Exception {      return getSqlSession().getMapper(this.mapperInterface);    }    ...  }
  •  72行:checkDaoConfig(),當(dāng)SpringBean容器初始化時(shí)候會調(diào)用到checkDaoConfig(),他是繼承類中的抽象方法

  •  95行:getSqlSession().getMapper(this.mapperInterface);,通過接口獲取Mapper(代理類),調(diào)用過程如下;

    •   DefaultSqlSession.getMapper(Class<T> type),獲取Mapper

    •   Configuration.getMapper(Class<T> type, SqlSession sqlSession),從配置中獲取

    •   MapperRegistry.getMapper(Class<T> type, SqlSession sqlSession),從注冊中心獲取到實(shí)例化生成     

public <T> T getMapper(Class<T> type, SqlSession sqlSession) {         final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);         if (mapperProxyFactory == null) {           throw new BindingException("Type " + type + " is not known to the MapperRegistry.");         }         try {           return mapperProxyFactory.newInstance(sqlSession);         } catch (Exception e) {           throw new BindingException("Error getting mapper instance. Cause: " + e, e);         }       }
  •   mapperProxyFactory.newInstance(sqlSession);,通過反射工程生成MapperProxy       

@SuppressWarnings("unchecked")          protected T newInstance(MapperProxy<T> mapperProxy) {            return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);          }          public T newInstance(SqlSession sqlSession) {            final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);            return newInstance(mapperProxy);          }

MapperProxy.java & 部分截取

public class MapperProxy<T> implements InvocationHandler, Serializable {    private static final long serialVersionUID = -6424540398559729838L;    private final SqlSession sqlSession;    private final Class<T> mapperInterface;    private final Map<Method, MapperMethod> methodCache;    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {      this.sqlSession = sqlSession;      this.mapperInterface = mapperInterface;      this.methodCache = methodCache;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {      try {        if (Object.class.equals(method.getDeclaringClass())) {          return method.invoke(this, args);        } else if (isDefaultMethod(method)) {          return invokeDefaultMethod(proxy, method, args);        }      } catch (Throwable t) {        throw ExceptionUtil.unwrapThrowable(t);      }      final MapperMethod mapperMethod = cachedMapperMethod(method);      return mapperMethod.execute(sqlSession, args);    }    private MapperMethod cachedMapperMethod(Method method) {      MapperMethod mapperMethod = methodCache.get(method);      if (mapperMethod == null) {        mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());        methodCache.put(method, mapperMethod);      }      return mapperMethod;    }    @UsesJava7    private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)        throws Throwable {      final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class          .getDeclaredConstructor(Class.class, int.class);      if (!constructor.isAccessible()) {        constructor.setAccessible(true);      }      final Class<?> declaringClass = method.getDeclaringClass();      return constructor          .newInstance(declaringClass,              MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED                  | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)          .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);    }    ...  }
  •  58行:final MapperMethod mapperMethod = cachedMapperMethod(method);,從緩存中獲取MapperMethod

  •  59行:mapperMethod.execute(sqlSession, args);,執(zhí)行SQL語句,并返回結(jié)果(到這關(guān)于查詢獲取結(jié)果就到骨頭(干)層了);INSERT、UPDATE、DELETE、SELECT 

public Object execute(SqlSession sqlSession, Object[] args) {     Object result;     switch (command.getType()) {       case INSERT: {       Object param = method.convertArgsToSqlCommandParam(args);         result = rowCountResult(sqlSession.insert(command.getName(), param));         break;       }       case UPDATE: {         Object param = method.convertArgsToSqlCommandParam(args);         result = rowCountResult(sqlSession.update(command.getName(), param));         break;       }       case DELETE: {         Object param = method.convertArgsToSqlCommandParam(args);         result = rowCountResult(sqlSession.delete(command.getName(), param));         break;       }       case SELECT:         if (method.returnsVoid() && method.hasResultHandler()) {           executeWithResultHandler(sqlSession, args);           result = null;         } else if (method.returnsMany()) {           result = executeForMany(sqlSession, args);         } else if (method.returnsMap()) {           result = executeForMap(sqlSession, args);         } else if (method.returnsCursor()) {           result = executeForCursor(sqlSession, args);         } else {           Object param = method.convertArgsToSqlCommandParam(args);           result = sqlSession.selectOne(command.getName(), param);         }         break;       case FLUSH:         result = sqlSession.flushStatements();         break;       default:         throw new BindingException("Unknown execution method for: " + command.getName());     }     if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {       throw new BindingException("Mapper method '" + command.getName()            + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");    }     return result;   }

以上對于MapperScannerConfigurer這一層就分析完了,從掃描定義注入到為Spring容器準(zhǔn)備Bean的信息,代理、反射、SQL執(zhí)行,基本就包括全部核心內(nèi)容了,接下來在分析下SqlSessionFactoryBean

3. SqlSession容器工廠初始化(SqlSessionFactoryBean)

SqlSessionFactoryBean初始化過程中需要對一些自身內(nèi)容進(jìn)行處理,因此也需要實(shí)現(xiàn)如下接口;

  •  FactoryBean<SqlSessionFactory>

  •  InitializingBean -> void afterPropertiesSet() throws Exception

  •  ApplicationListener<ApplicationEvent>

Mybatis接口沒有實(shí)現(xiàn)類為什么可以執(zhí)行增刪改查

以上的流程其實(shí)已經(jīng)很清晰的描述整個(gè)核心流程,但同樣對于新手上路會有障礙,那么!好,繼續(xù)!

SqlSessionFactoryBean.java & 部分截取

public void afterPropertiesSet() throws Exception {    notNull(dataSource, "Property 'dataSource' is required");    notNull(sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");    state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null),              "Property 'configuration' and 'configLocation' can not specified with together");    this.sqlSessionFactory = buildSqlSessionFactory();  }
  •  afterPropertiesSet(),InitializingBean接口為bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是繼承該接口的類,在初始化bean的時(shí)候都會執(zhí)行該方法。

  •  380行:buildSqlSessionFactory();內(nèi)部方法構(gòu)建,核心功能繼續(xù)往下看。

SqlSessionFactoryBean.java & 部分截取

protected SqlSessionFactory buildSqlSessionFactory() throws IOException {    Configuration configuration;    XMLConfigBuilder xmlConfigBuilder = null;    ...   if (!isEmpty(this.mapperLocations)) {      for (Resource mapperLocation : this.mapperLocations) {       if (mapperLocation == null) {          continue;        }        try {          XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),              configuration, mapperLocation.toString(), configuration.getSqlFragments());          xmlMapperBuilder.parse();        } catch (Exception e) {          throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);        } finally {          ErrorContext.instance().reset();        }        if (LOGGER.isDebugEnabled()) {          LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'");        }      }    } else {      if (LOGGER.isDebugEnabled()) {        LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found");      }    }    return this.sqlSessionFactoryBuilder.build(configuration);  }
  •  513行:for (Resource mapperLocation : this.mapperLocations) 循環(huán)解析Mapper內(nèi)容

  •  519行:XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(...) 解析XMLMapperBuilder

  •  521行:xmlMapperBuilder.parse() 執(zhí)行解析,具體如下;

XMLMapperBuilder.java & 部分截取

public class XMLMapperBuilder extends BaseBuilder {     private final XPathParser parser;     private final MapperBuilderAssistant builderAssistant;     private final Map<String, XNode> sqlFragments;     private final String resource;     private void bindMapperForNamespace() {       String namespace = builderAssistant.getCurrentNamespace();      if (namespace != null) {         Class<?> boundType = null;         try {           boundType = Resources.classForName(namespace);         } catch (ClassNotFoundException e) {           //ignore, bound type is not required         }         if (boundType != null) {           if (!configuration.hasMapper(boundType)) {             // Spring may not know the real resource name so we set a flag             // to prevent loading again this resource from the mapper interface             // look at MapperAnnotationBuilder#loadXmlResource             configuration.addLoadedResource("namespace:" + namespace);             configuration.addMapper(boundType);           }         }       }     }  }
  •  這里413行非常重要,configuration.addMapper(boundType);,真正到了添加Mapper到配置中心

MapperRegistry.java & 部分截取

public class MapperRegistry {    public <T> void addMapper(Class<T> type) {      if (type.isInterface()) {        if (hasMapper(type)) {          throw new BindingException("Type " + type + " is already known to the MapperRegistry.");        }        boolean loadCompleted = false;        try {          knownMappers.put(type, new MapperProxyFactory<T>(type));          // It's important that the type is added before the parser is run          // otherwise the binding may automatically be attempted by the          // mapper parser. If the type is already known, it won't try.          MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);          parser.parse();          loadCompleted = true;        } finally {          if (!loadCompleted) {            knownMappers.remove(type);          }        }      }    }  }
  •  67行:創(chuàng)建代理工程knownMappers.put(type, new MapperProxyFactory<T>(type));

截至到這,MapperScannerConfigurer、SqlSessionFactoryBean,兩個(gè)類干的事情就相融合了;

  •  第一個(gè)用于掃描Dao接口設(shè)置代理類注冊到IOC中,用于后續(xù)生成Bean實(shí)體類,MapperFactoryBean,并可以通過mapperInterface從Configuration獲取Mapper

  •  另一個(gè)用于生成SqlSession工廠初始化,解析Mapper里的XML配置進(jìn)行動態(tài)代理MapperProxyFactory->MapperProxy注入到Configuration的Mapper

  •  最終在注解類的幫助下進(jìn)行方法注入,等執(zhí)行操作時(shí)候即可獲得動態(tài)代理對象,從而執(zhí)行相應(yīng)的CRUD操作 

@Resource    private ISchoolDao schoolDao;   schoolDao.querySchoolInfoById(1L);

六、總結(jié)

  •  分析過程較長篇幅也很大,不一定一天就能看懂整個(gè)流程,但當(dāng)耐下心來一點(diǎn)點(diǎn)研究,還是可以獲得很多的收獲的。以后在遇到這類的異常就可以迎刃而解了,同時(shí)也有助于面試、招聘!

  •  之所以分析Mybatis最開始是想在Dao上加自定義注解,發(fā)現(xiàn)切面攔截不到。想到這是被動態(tài)代理的類,之后層層往往下扒直到MapperProxy.invoke!當(dāng)然,Mybatis提供了自定義插件開發(fā)。

  •  以上的源碼分析只是對部分核心內(nèi)容進(jìn)行分析,如果希望了解全部可以參考資料;MyBatis 3源碼深度解析,并調(diào)試代碼。IDEA中還是很方便看源碼的,包括可以查看類圖、調(diào)用順序等。

  •  mybatis、mybatis-spring中其實(shí)最重要的是將Mapper配置文件解析與接口類組裝成代理類進(jìn)行映射,以此來方便對數(shù)據(jù)庫的CRUD操作。從源碼分析后,可以獲得更多的編程經(jīng)驗(yàn)(套路)。

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI