面试必问 | 聊聊 MyBatis 执行流程?

开发 后端
随着互联网的发展,越来越多的公司摒弃了Hibernate,而选择拥抱了MyBatis。而且,很多大厂在面试的时候喜欢问MyBatis底层的原理和源码实现。

[[439461]]

随着互联网的发展,越来越多的公司摒弃了Hibernate,而选择拥抱了MyBatis。而且,很多大厂在面试的时候喜欢问MyBatis底层的原理和源码实现。

总之,MyBatis几乎成为了Java开发人员必须深入掌握的框架技术,今天,我们就一起来深入分析MyBatis源码。文章有点长,建议先收藏后慢慢研究。整体三万字左右,全程高能,小伙伴们可慢慢研究。

文章已收录到:

https://github.com/sunshinelyz/technology-binghe

https://gitee.com/binghe001/technology-binghe

本文主要结构如下所示。

MyBatis源码解析

大家应该都知道Mybatis源码也是对Jbdc的再一次封装,不管怎么进行包装,还是会有获取链接、preparedStatement、封装参数、执行这些步骤的。

配置解析过程

  1. String resource = "mybatis-config.xml"
  2. //1.读取resources下面的mybatis-config.xml文件 
  3. InputStream inputStream = Resources.getResourceAsStream(resource); 
  4. //2.使用SqlSessionFactoryBuilder创建SqlSessionFactory 
  5. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
  6. //3.通过sqlSessionFactory创建SqlSession 
  7. SqlSession sqlSession = sqlSessionFactory.openSession(); 

Resources.getResourceAsStream(resource)读取文件

  1. public static InputStream getResourceAsStream(String resource) throws IOException { 
  2.  return getResourceAsStream(null, resource); 
  3. }  
  4. //loader赋值为null 
  5. public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException { 
  6.  InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader); 
  7.  if (in == null) { 
  8.   throw new IOException("Could not find resource " + resource); 
  9.  }  
  10.  return in
  11. //classLoader为null 
  12. public InputStream getResourceAsStream(String resource, ClassLoader classLoader) { 
  13.  return getResourceAsStream(resource, getClassLoaders(classLoader)); 
  14. }  
  15. //classLoader类加载 
  16. InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) { 
  17.  for (ClassLoader cl : classLoader) { 
  18.   if (null != cl) { 
  19.    //加载指定路径文件流 
  20.    InputStream returnValue = cl.getResourceAsStream(resource); 
  21.    // now, some class loaders want this leading "/", so we'll add it and try again if we didn't find the resource 
  22.    if (null == returnValue) { 
  23.     returnValue = cl.getResourceAsStream("/" + resource); 
  24.    }  
  25.    if (null != returnValue) { 
  26.     return returnValue; 
  27.    } 
  28.   } 
  29.  }  
  30.  return null

总结:主要是通过ClassLoader.getResourceAsStream()方法获取指定的classpath路径下的Resource 。

通过SqlSessionFactoryBuilder创建SqlSessionFactory

  1. //SqlSessionFactoryBuilder是一个建造者模式 
  2. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 
  3. public SqlSessionFactory build(InputStream inputStream) { 
  4.  return build(inputStream, nullnull); 
  5. //XMLConfigBuilder也是建造者模式 
  6. public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { 
  7.  try { 
  8.   XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); 
  9.   return build(parser.parse()); 
  10.  } catch (Exception e) { 
  11.   throw ExceptionFactory.wrapException("Error building SqlSession.", e); 
  12.  } finally { 
  13.   ErrorContext.instance().reset(); 
  14.   try { 
  15.    inputStream.close(); 
  16.   } catch (IOException e) { 
  17.    // Intentionally ignore. Prefer previous error. 
  18.   } 
  19.  } 
  20. //接下来进入XMLConfigBuilder构造函数 
  21. public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) { 
  22.  this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props); 
  23. //接下来进入this后,初始化Configuration 
  24. private XMLConfigBuilder(XPathParser parser, String environment, Properties props) { 
  25.  super(new Configuration()); 
  26.  ErrorContext.instance().resource("SQL Mapper Configuration"); 
  27.  this.configuration.setVariables(props); 
  28.  this.parsed = false
  29.  this.environment = environment; 
  30.  this.parser = parser; 
  31. //其中parser.parse()负责解析xml,build(configuration)创建SqlSessionFactory 
  32. return build(parser.parse()); 

parser.parse()解析xml

  1. public Configuration parse() { 
  2.  //判断是否重复解析 
  3.  if (parsed) { 
  4.   throw new BuilderException("Each XMLConfigBuilder can only be used once."); 
  5.  }  
  6.  parsed = true
  7.  //读取配置文件一级节点configuration 
  8.  parseConfiguration(parser.evalNode("/configuration")); 
  9.  return configuration; 
  1. private void parseConfiguration(XNode root) { 
  2.  try { 
  3.   //properties 标签,用来配置参数信息,比如最常见的数据库连接信息 
  4.   propertiesElement(root.evalNode("properties")); 
  5.   Properties settings = settingsAsProperties(root.evalNode("settings")); 
  6.   loadCustomVfs(settings); 
  7.   loadCustomLogImpl(settings); 
  8.   //实体别名两种方式:1.指定单个实体;2.指定包 
  9.   typeAliasesElement(root.evalNode("typeAliases")); 
  10.   //插件 
  11.   pluginElement(root.evalNode("plugins")); 
  12.   //用来创建对象(数据库数据映射成java对象时) 
  13.   objectFactoryElement(root.evalNode("objectFactory")); 
  14.   objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); 
  15.   reflectorFactoryElement(root.evalNode("reflectorFactory")); 
  16.   settingsElement(settings); 
  17.   // read it after objectFactory and objectWrapperFactory issue #631 
  18.   //数据库环境 
  19.   environmentsElement(root.evalNode("environments")); 
  20.   databaseIdProviderElement(root.evalNode("databaseIdProvider")); 
  21.   //数据库类型和Java数据类型的转换 
  22.   typeHandlerElement(root.evalNode("typeHandlers")); 
  23.   //这个是对数据库增删改查的解析 
  24.   mapperElement(root.evalNode("mappers")); 
  25.  } catch (Exception e) { 
  26.   throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); 
  27.  } 

总结:parseConfiguration完成的是解析configuration下的标签。

  1. private void mapperElement(XNode parent) throws Exception { 
  2.  if (parent != null) { 
  3.    for (XNode child : parent.getChildren()) { 
  4.    //解析<package name=""/> 
  5.    if ("package".equals(child.getName())) { 
  6.     String mapperPackage = child.getStringAttribute("name"); 
  7.     //包路径存到mapperRegistry中 
  8.     configuration.addMappers(mapperPackage); 
  9.    } else { 
  10.     //解析<mapper url="" class="" resource=""></mapper> 
  11.     String resource = child.getStringAttribute("resource"); 
  12.     String url = child.getStringAttribute("url"); 
  13.     String mapperClass = child.getStringAttribute("class"); 
  14.     if (resource != null && url == null && mapperClass == null) { 
  15.      ErrorContext.instance().resource(resource); 
  16.      //读取Mapper.xml文件 
  17.      InputStream inputStream = Resources.getResourceAsStream(resource); 
  18.      XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, 
  19.      configuration, resource, configuration.getSqlFragments()); 
  20.      mapperParser.parse(); 
  21.     } else if (resource == null && url != null && mapperClass == null) { 
  22.      ErrorContext.instance().resource(url); 
  23.      InputStream inputStream = Resources.getUrlAsStream(url); 
  24.      XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, 
  25.      configuration, url, configuration.getSqlFragments()); 
  26.      mapperParser.parse(); 
  27.     } else if (resource == null && url == null && mapperClass != null) { 
  28.      Class<?> mapperInterface = Resources.classForName(mapperClass); 
  29.      configuration.addMapper(mapperInterface); 
  30.     } else { 
  31.      throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one."); 
  32.     } 
  33.    } 
  34.   } 
  35.  } 

总结:通过解析configuration.xml文件,获取其中的Environment、Setting,重要的是将下的所有解析出来之后添加到 Configuration,Configuration类似于配置中心,所有的配置信息都在这里。

mapperParser.parse()对 Mapper 映射器的解析

  1. public void parse() { 
  2.  if (!configuration.isResourceLoaded(resource)) { 
  3.   //解析所有的子标签 
  4.   configurationElement(parser.evalNode("/mapper")); 
  5.   configuration.addLoadedResource(resource); 
  6.   //把namespace(接口类型)和工厂类绑定起来 
  7.   bindMapperForNamespace(); 
  8.  } 
  9.  parsePendingResultMaps(); 
  10.  parsePendingCacheRefs(); 
  11.  parsePendingStatements(); 
  12. }  
  13. //这里面解析的是Mapper.xml的标签 
  14. private void configurationElement(XNode context) { 
  15.  try { 
  16.   String namespace = context.getStringAttribute("namespace"); 
  17.   if (namespace == null || namespace.equals("")) { 
  18.    throw new BuilderException("Mapper's namespace cannot be empty"); 
  19.   }  
  20.   builderAssistant.setCurrentNamespace(namespace); 
  21.   //对其他命名空间缓存配置的引用 
  22.   cacheRefElement(context.evalNode("cache-ref")); 
  23.   //对给定命名空间的缓存配置 
  24.   cacheElement(context.evalNode("cache")); 
  25.   parameterMapElement(context.evalNodes("/mapper/parameterMap")); 
  26.   //是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象 
  27.   resultMapElements(context.evalNodes("/mapper/resultMap")); 
  28.   //可被其他语句引用的可重用语句块 
  29.   sqlElement(context.evalNodes("/mapper/sql")); 
  30.   //获得MappedStatement对象(增删改查标签) 
  31.   buildStatementFromContext(context.evalNodes("select|insert|update|delete")); 
  32.  } catch (Exception e) { 
  33.   throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e); 
  34.  } 
  35. //获得MappedStatement对象(增删改查标签) 
  36. private void buildStatementFromContext(List<XNode> list) { 
  37.  if (configuration.getDatabaseId() != null) { 
  38.   buildStatementFromContext(list, configuration.getDatabaseId()); 
  39.  }  
  40.  buildStatementFromContext(list, null); 
  41. //获得MappedStatement对象(增删改查标签) 
  42. private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) { 
  43.  //循环增删改查标签 
  44.  for (XNode context : list) { 
  45.   final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId); 
  46.   try { 
  47.    //解析insert/update/select/del中的标签 
  48.    statementParser.parseStatementNode(); 
  49.   } catch (IncompleteElementException e) { 
  50.    configuration.addIncompleteStatement(statementParser); 
  51.   } 
  52.  } 
  53. public void parseStatementNode() { 
  54.  //在命名空间中唯一的标识符,可以被用来引用这条语句 
  55.  String id = context.getStringAttribute("id"); 
  56.  //数据库厂商标识 
  57.  String databaseId = context.getStringAttribute("databaseId"); 
  58.  if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) { 
  59.   return
  60.  }  
  61.  String nodeName = context.getNode().getNodeName(); 
  62.  SqlCommandType sqlCommandType = 
  63.  SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH)); 
  64.  boolean isSelect = sqlCommandType == SqlCommandType.SELECT
  65.  //flushCache和useCache都和二级缓存有关 
  66.  //将其设置为true后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false 
  67.  boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect); 
  68.  //将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true 
  69.  boolean useCache = context.getBooleanAttribute("useCache", isSelect); 
  70.  boolean resultOrdered = context.getBooleanAttribute("resultOrdered"false); 
  71.  // Include Fragments before parsing 
  72.  XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant); 
  73.  includeParser.applyIncludes(context.getNode()); 
  74.  //会传入这条语句的参数类的完全限定名或别名 
  75.  String parameterType = context.getStringAttribute("parameterType"); 
  76.  Class<?> parameterTypeClass = resolveClass(parameterType); 
  77.  String lang = context.getStringAttribute("lang"); 
  78.  LanguageDriver langDriver = getLanguageDriver(lang); 
  79.  // Parse selectKey after includes and remove them. 
  80.  processSelectKeyNodes(id, parameterTypeClass, langDriver); 
  81.  // Parse the SQL (pre: <selectKey> and <include> were parsed and removed) 
  82.  KeyGenerator keyGenerator; 
  83.  String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX; 
  84.  keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true); 
  85.  if (configuration.hasKeyGenerator(keyStatementId)) { 
  86.   keyGenerator = configuration.getKeyGenerator(keyStatementId); 
  87.  } else { 
  88.   keyGenerator = context.getBooleanAttribute("useGeneratedKeys", configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType)) ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE; 
  89.  }  
  90.  SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass); 
  91.  StatementType statementType = 
  92.  StatementType.valueOf(context.getStringAttribute("statementType"
  93.  StatementType.PREPARED.toString())); 
  94.  Integer fetchSize = context.getIntAttribute("fetchSize"); 
  95.  Integer timeout = context.getIntAttribute("timeout"); 
  96.  String parameterMap = context.getStringAttribute("parameterMap"); 
  97.  //从这条语句中返回的期望类型的类的完全限定名或别名 
  98.  String resultType = context.getStringAttribute("resultType"); 
  99.  Class<?> resultTypeClass = resolveClass(resultType); 
  100.  //外部resultMap的命名引用 
  101.  String resultMap = context.getStringAttribute("resultMap"); 
  102.  String resultSetType = context.getStringAttribute("resultSetType"); 
  103.  ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType); 
  104.  String keyProperty = context.getStringAttribute("keyProperty"); 
  105.  String keyColumn = context.getStringAttribute("keyColumn"); 
  106.  String resultSets = context.getStringAttribute("resultSets"); 
  107.  builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, 
  108.  fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, 
  109.  resultSetTypeEnum, flushCache, useCache, resultOrdered, 
  110.  keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets); 
  111. public MappedStatement addMappedStatement( 
  112.  String id, 
  113.  SqlSource sqlSource, 
  114.  StatementType statementType, 
  115.  SqlCommandType sqlCommandType, 
  116.  Integer fetchSize, 
  117.  Integer timeout, 
  118.  String parameterMap, 
  119.  Class<?> parameterType, 
  120.  String resultMap, 
  121.  Class<?> resultType, 
  122.  ResultSetType resultSetType, 
  123.  boolean flushCache, 
  124.  boolean useCache, 
  125.  boolean resultOrdered, 
  126.  KeyGenerator keyGenerator, 
  127.  String keyProperty, 
  128.  String keyColumn, 
  129.  String databaseId, 
  130.  LanguageDriver lang, 
  131.  String resultSets) { 
  132.  if (unresolvedCacheRef) { 
  133.   throw new IncompleteElementException("Cache-ref not yet resolved"); 
  134.  }  
  135.   id = applyCurrentNamespace(id, false); 
  136.   boolean isSelect = sqlCommandType == SqlCommandType.SELECT
  137.   MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, 
  138.   id, sqlSource, sqlCommandType) 
  139.   .resource(resource) 
  140.   .fetchSize(fetchSize) 
  141.   .timeout(timeout) 
  142.   .statementType(statementType) 
  143.   .keyGenerator(keyGenerator) 
  144.   .keyProperty(keyProperty) 
  145.   .keyColumn(keyColumn) 
  146.   .databaseId(databaseId) 
  147.   .lang(lang) 
  148.   .resultOrdered(resultOrdered) 
  149.   .resultSets(resultSets) 
  150.   .resultMaps(getStatementResultMaps(resultMap, resultType, id)) 
  151.   .resultSetType(resultSetType) 
  152.   .flushCacheRequired(valueOrDefault(flushCache, !isSelect)) 
  153.   .useCache(valueOrDefault(useCache, isSelect)) 
  154.   .cache(currentCache); 
  155.   ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, 
  156.   parameterType, id); 
  157.   if (statementParameterMap != null) { 
  158.    statementBuilder.parameterMap(statementParameterMap); 
  159.   }  
  160.   MappedStatement statement = statementBuilder.build(); 
  161.   //持有在configuration中 
  162.   configuration.addMappedStatement(statement); 
  163.   return statement; 
  164. public void addMappedStatement(MappedStatement ms){ 
  165. //ms.getId = mapper.UserMapper.getUserById 
  166. //ms = MappedStatement等于每一个增删改查的标签的里的数据 
  167.  mappedStatements.put(ms.getId(), ms); 
  168. //最终存放到mappedStatements中,mappedStatements存放的是一个个的增删改查 
  169. protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection").conflictMessageProducer((savedValue, targetValue) -> 
  170. ". please check " + savedValue.getResource() + " and " + targetValue.getResource()); 

解析bindMapperForNamespace()方法

把 namespace(接口类型)和工厂类绑定起来。

  1. private void bindMapperForNamespace() { 
  2.  //当前Mapper的命名空间 
  3.  String namespace = builderAssistant.getCurrentNamespace(); 
  4.  if (namespace != null) { 
  5.   Class<?> boundType = null
  6.   try { 
  7.    //interface mapper.UserMapper这种 
  8.    boundType = Resources.classForName(namespace); 
  9.   } catch (ClassNotFoundException e) { 
  10.   }  
  11.   if (boundType != null) { 
  12.    if (!configuration.hasMapper(boundType)) { 
  13.     configuration.addLoadedResource("namespace:" + namespace); 
  14.     configuration.addMapper(boundType); 
  15.    } 
  16.   } 
  17.  } 
  18. public <T> void addMapper(Class<T> type) { 
  19.  mapperRegistry.addMapper(type); 
  20. }  
  21. public <T> void addMapper(Class<T> type) { 
  22.  if (type.isInterface()) { 
  23.   if (hasMapper(type)) { 
  24.    throw new BindingException("Type " + type + " is already known to the MapperRegistry."); 
  25.   }  
  26.   boolean loadCompleted = false
  27.   try { 
  28.    //接口类型(key)->工厂类 
  29.    knownMappers.put(type, new MapperProxyFactory<>(type)); 
  30.    MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type); 
  31.    parser.parse(); 
  32.    loadCompleted = true
  33.   } finally { 
  34.    if (!loadCompleted) { 
  35.     knownMappers.remove(type); 
  36.    } 
  37.   } 
  38.  } 

生成SqlSessionFactory对象

XMLMapperBuilder.parse()方法,是对 Mapper 映射器的解析里面有两个方法:

(1)configurationElement()解析所有的子标签,最终解析Mapper.xml中的insert/update/delete/select标签的id(全路径)组成key和整个标签和数据连接组成MappedStatement存放到Configuration中的 mappedStatements这个map里面。

(2)bindMapperForNamespace()是把接口类型(interface mapper.UserMapper)和工厂类存到放MapperRegistry中的knownMappers里面。

SqlSessionFactory的创建

  1. public SqlSessionFactory build(Configuration config) { 
  2.  return new DefaultSqlSessionFactory(config); 

直接把Configuration当做参数,直接new一个DefaultSqlSessionFactory。

SqlSession会话的创建过程

mybatis操作的时候跟数据库的每一次连接,都需要创建一个会话,我们用openSession()方法来创建。这个会话里面需要包含一个Executor用来执行 SQL。Executor又要指定事务类型和执行器的类型。

创建Transaction(两种方式)

属性 产生工厂类 产生事务
JDBC JbdcTransactionFactory JdbcTransaction
MANAGED ManagedTransactionFactory ManagedTransaction
  • 如果配置的是 JDBC,则会使用Connection 对象的 commit()、rollback()、close()管理事务。
  • 如果配置成MANAGED,会把事务交给容器来管理,比如 JBOSS,Weblogic。
  1. SqlSession sqlSession = sqlSessionFactory.openSession(); 
  1. public SqlSession openSession() { 
  2.  //configuration中有默认赋值protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE 
  3.  return openSessionFromDataSource(configuration.getDefaultExecutorType(), nullfalse); 
  1. <environments default="development"
  2.  <environment id="development"
  3.   <transactionManager type="JDBC"/> 
  4.   <dataSource type="POOLED"
  5.    <property name="driver" value="${driver}"/> 
  6.    <property name="url" value="${url}"/> 
  7.    <property name="username" value="${username}"/> 
  8.    <property name="password" value="${password}"/> 
  9.   </dataSource> 
  10.  </environment> 
  11. </environments> 

创建Executor

  1. //ExecutorType是SIMPLE,一共有三种SIMPLE(SimpleExecutor)、REUSE(ReuseExecutor)、BATCH(BatchExecutor) 
  2. private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { 
  3.  Transaction tx = null
  4.  try { 
  5.   //xml中的development节点 
  6.   final Environment environment = configuration.getEnvironment(); 
  7.   //type配置的是Jbdc所以生成的是JbdcTransactionFactory工厂类 
  8.   final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); 
  9.   //Jdbc生成JbdcTransactionFactory生成JbdcTransaction 
  10.   tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); 
  11.   //创建CachingExecutor执行器 
  12.   final Executor executor = configuration.newExecutor(tx, execType); 
  13.   //创建DefaultSqlSession属性包括 Configuration、Executor对象 
  14.   return new DefaultSqlSession(configuration, executor, autoCommit); 
  15.  } catch (Exception e) { 
  16.   closeTransaction(tx); // may have fetched a connection so lets call 
  17.   close() 
  18.   throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e); 
  19.  } finally { 
  20.   ErrorContext.instance().reset(); 
  21.  } 

获得Mapper对象

  1. UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 
  1. public T getMapper(Class type) { 
  2.  
  3. return configuration.getMapper(type, this); 
  4.  

mapperRegistry.getMapper是从MapperRegistry的knownMappers里面取的,knownMappers里面存的是接口类型(interface mapper.UserMapper)和工厂类(MapperProxyFactory)。

  1. public <T> T getMapper(Class<T> type, SqlSession sqlSession) { 
  2.  return mapperRegistry.getMapper(type, sqlSession); 

从knownMappers的Map里根据接口类型(interface mapper.UserMapper)取出对应的工厂类。

  1. public <T> T getMapper(Class<T> type, SqlSession sqlSession) { 
  2.  final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) 
  3.  knownMappers.get(type); 
  4.  if (mapperProxyFactory == null) { 
  5.   throw new BindingException("Type " + type + " is not known to the MapperRegistry."); 
  6.  }  
  7.  try { 
  8.   return mapperProxyFactory.newInstance(sqlSession); 
  9.  } catch (Exception e) { 
  10.   throw new BindingException("Error getting mapper instance. Cause: " + e, e); 
  11.  } 
  12. public T newInstance(SqlSession sqlSession) { 
  13.  final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); 
  14.  return newInstance(mapperProxy); 

这里通过JDK动态代理返回代理对象MapperProxy(org.apache.ibatis.binding.MapperProxy@6b2ea799)。

  1. protected T newInstance(MapperProxy<T> mapperProxy) { 
  2.  //mapperInterface是interface mapper.UserMapper  
  3.  return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new 
  4.  Class[] { mapperInterface }, mapperProxy); 
  1. UserMapper userMapper = sqlSession.getMapper(UserMapper.class); 

执行SQL

  1. User user = userMapper.getUserById(1); 

调用invoke代理方法

由于所有的 Mapper 都是 MapperProxy 代理对象,所以任意的方法都是执行MapperProxy 的invoke()方法。

  1. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
  2.  try { 
  3.   //判断是否需要去执行SQL还是直接执行方法 
  4.   if (Object.class.equals(method.getDeclaringClass())) { 
  5.    return method.invoke(this, args); 
  6.    //这里判断的是接口中的默认方法Default等 
  7.   } else if (isDefaultMethod(method)) { 
  8.    return invokeDefaultMethod(proxy, method, args); 
  9.   } 
  10.  } catch (Throwable t) { 
  11.   throw ExceptionUtil.unwrapThrowable(t); 
  12.  }  
  13.     //获取缓存,保存了方法签名和接口方法的关系 
  14.  final MapperMethod mapperMethod = cachedMapperMethod(method); 
  15.  return mapperMethod.execute(sqlSession, args); 

调用execute方法

这里使用的例子用的是查询所以走的是else分支语句。

  1. public Object execute(SqlSession sqlSession, Object[] args) { 
  2.  Object result; 
  3.  //根据命令类型走不行的操作command.getType()是select 
  4.  switch (command.getType()) { 
  5.   case INSERT: { 
  6.    Object param = method.convertArgsToSqlCommandParam(args); 
  7.    result = rowCountResult(sqlSession.insert(command.getName(), param)); 
  8.    break; 
  9.   }  
  10.   case UPDATE: { 
  11.    Object param = method.convertArgsToSqlCommandParam(args); 
  12.    result = rowCountResult(sqlSession.update(command.getName(), param)); 
  13.    break; 
  14.   }  
  15.   case DELETE: { 
  16.    Object param = method.convertArgsToSqlCommandParam(args); 
  17.    result = rowCountResult(sqlSession.delete(command.getName(), param)); 
  18.    break; 
  19.   }  
  20.   case SELECT
  21.    if (method.returnsVoid() && method.hasResultHandler()) { 
  22.     executeWithResultHandler(sqlSession, args); 
  23.     result = null
  24.    } else if (method.returnsMany()) { 
  25.     result = executeForMany(sqlSession, args); 
  26.    } else if (method.returnsMap()) { 
  27.     result = executeForMap(sqlSession, args); 
  28.    } else if (method.returnsCursor()) { 
  29.     result = executeForCursor(sqlSession, args); 
  30.    } else { 
  31.     //将参数转换为SQL的参数 
  32.     Object param = method.convertArgsToSqlCommandParam(args); 
  33.     result = sqlSession.selectOne(command.getName(), param); 
  34.     if (method.returnsOptional() 
  35.     && (result == null || 
  36.     !method.getReturnType().equals(result.getClass()))) { 
  37.      result = Optional.ofNullable(result); 
  38.     } 
  39.    } 
  40.    break; 
  41.   case FLUSH: 
  42.    result = sqlSession.flushStatements(); 
  43.    break; 
  44.   default
  45.    throw new BindingException("Unknown execution method for: " + command.getName()); 
  46.  }  
  47.  if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { 
  48.   throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); 
  49.  }  
  50.  return result; 

调用selectOne其实是selectList

selectOne查询一个和查询多个其实是一样的。

  1. public <T> T selectOne(String statement, Object parameter) { 
  2.  // Popular vote was to return null on 0 results and throw exception on too many. 
  3.  List<T> list = this.selectList(statement, parameter); 
  4.  if (list.size() == 1) { 
  5.   return list.get(0); 
  6.  } else if (list.size() > 1) { 
  7.   throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); 
  8.  } else { 
  9.   return null
  10.  } 
  1. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) { 
  2.  try { 
  3.   //从Configuration里的mappedStatements里根据key(id的全路径)获取MappedStatement 对象 
  4.   MappedStatement ms = configuration.getMappedStatement(statement); 
  5.   return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); 
  6.  } catch (Exception e) { 
  7.   throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); 
  8.  } finally { 
  9.   ErrorContext.instance().reset(); 
  10.  } 

mappedStatements对象如图

MappedStatement对象如图

执行query方法

创建CacheKey

从 BoundSql 中获取SQL信息,创建 CacheKey。这个CacheKey就是缓存的Key。

  1. public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { 
  2.  //创建缓存Key 
  3.  BoundSql boundSql = ms.getBoundSql(parameterObject); 
  4.  //key = -575461213:-771016147:mapper.UserMapper.getUserById:0:2147483647:select * from test_user where id = ?:1:development 
  5.  CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql); 
  6.  return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); 
  1. public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { 
  2.  Cache cache = ms.getCache(); 
  3.  if (cache != null) { 
  4.   flushCacheIfRequired(ms); 
  5.   if (ms.isUseCache() && resultHandler == null) { 
  6.    ensureNoOutParams(ms, boundSql); 
  7.    @SuppressWarnings("unchecked"
  8.    List<E> list = (List<E>) tcm.getObject(cache, key); 
  9.    if (list == null) { 
  10.     list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); 
  11.     tcm.putObject(cache, key, list); // issue #578 and #116 
  12.    }  
  13.    return list; 
  14.   } 
  15.  } 
  16.  return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); 

清空本地缓存

  1. public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { 
  2.  ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId()); 
  3.  if (closed) { 
  4.   throw new ExecutorException("Executor was closed."); 
  5.  }  
  6.  //queryStack 用于记录查询栈,防止递归查询重复处理缓存 
  7.  //flushCache=true 的时候,会先清理本地缓存(一级缓存) 
  8.  if (queryStack == 0 && ms.isFlushCacheRequired()) { 
  9.   //清空本地缓存 
  10.   clearLocalCache(); 
  11.  }  
  12.  List<E> list; 
  13.  try { 
  14.   queryStack++; 
  15.   list = resultHandler == null ? (List<E>) localCache.getObject(key) : null
  16.   if (list != null) { 
  17.    handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); 
  18.   } else { 
  19.    //如果没有缓存,会从数据库查询:queryFromDatabase() 
  20.    list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql); 
  21.   } 
  22.  } finally { 
  23.   queryStack--; 
  24.  }  
  25.  if (queryStack == 0) { 
  26.   for (DeferredLoad deferredLoad : deferredLoads) { 
  27.   deferredLoad.load(); 
  28.   }  
  29.   // issue #601 
  30.   deferredLoads.clear(); 
  31.   //如果 LocalCacheScope == STATEMENT,会清理本地缓存 
  32.   if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) { 
  33.    // issue #482 
  34.    clearLocalCache(); 
  35.   } 
  36.  }  
  37.  return list; 

从数据库查询

  1. private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { 
  2.  List<E> list; 
  3.  //先在缓存用占位符占位 
  4.  localCache.putObject(key, EXECUTION_PLACEHOLDER); 
  5.  try { 
  6.   //执行Executor 的 doQuery(),默认是SimpleExecutor 
  7.   list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql); 
  8.  } finally { 
  9.   //执行查询后,移除占位符 
  10.   localCache.removeObject(key); 
  11.  }  
  12.  //从新放入数据 
  13.  localCache.putObject(key, list); 
  14.  if (ms.getStatementType() == StatementType.CALLABLE) { 
  15.   localOutputParameterCache.putObject(key, parameter); 
  16.  }  
  17.  return list; 

执行doQuery

  1. public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException { 
  2.  Statement stmt = null
  3.  try { 
  4.   Configuration configuration = ms.getConfiguration(); 
  5.   StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); 
  6.   stmt = prepareStatement(handler, ms.getStatementLog()); 
  7.   return handler.query(stmt, resultHandler); 
  8.  } finally { 
  9.   closeStatement(stmt); 
  10.  } 

源码总结

总体上来说,MyBatis的源码还是比较简单的,只要大家踏下心来,花个两三天仔细研究下,基本上都能弄明白源码的主体脉络。为了方便小伙伴们理解,冰河为大家整理了一个MyBatis整体执行的流程图。

 

好了,今天就到这儿吧,我是冰河,我们下期见~~。

本文转载自微信公众号「冰河技术」,可以通过以下二维码关注。转载本文请联系冰河技术公众号。

 

责任编辑:武晓燕 来源: 冰河技术
相关推荐

2023-02-06 07:01:51

2021-12-06 11:03:57

JVM性能调优

2021-12-27 08:22:18

Kafka消费模型

2020-07-28 08:59:22

JavahreadLocal面试

2023-06-07 08:08:43

JVM内存模型

2023-02-03 07:24:49

双亲委派模型

2023-08-15 15:33:29

线程池线程数

2020-09-29 15:24:07

面试数据结构Hashmap

2020-02-18 14:25:51

Java线程池拒绝策略

2019-03-15 19:41:39

MySQL面试数据库

2023-02-17 08:02:45

@Autowired@Resource

2023-02-01 07:15:16

2020-11-05 13:12:47

红黑树

2024-01-05 14:20:55

MySQL索引优化器

2021-09-08 10:42:45

前端面试性能指标

2023-02-15 07:03:41

跨域问题面试安全

2021-12-13 11:12:41

Spring事务失效

2021-09-10 18:47:22

Redis淘汰策略

2023-02-02 07:06:10

2020-10-12 18:00:39

JavaAQS代码
点赞
收藏

51CTO技术栈公众号