当前位置:   article > 正文

面试官:简单聊聊MyBatis执行流程

面试官:简单聊聊MyBatis执行流程

本文分享自华为云社区《面试必问|聊聊MyBatis执行流程?》,作者: 冰 河。

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. }
  12. //classLoader为null
  13. public InputStream getResourceAsStream(String resource, ClassLoader classLoader) {
  14. return getResourceAsStream(resource, getClassLoaders(classLoader));
  15. }
  16. //classLoader类加载
  17. InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
  18. for (ClassLoader cl : classLoader) {
  19. if (null != cl) {
  20. //加载指定路径文件流
  21. InputStream returnValue = cl.getResourceAsStream(resource);
  22. // now, some class loaders want this leading "/", so we'll add it and try again if we didn't find the resource
  23. if (null == returnValue) {
  24. returnValue = cl.getResourceAsStream("/" + resource);
  25. }
  26. if (null != returnValue) {
  27. return returnValue;
  28. }
  29. }
  30. }
  31. return null;
  32. }

总结:主要是通过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, null, null);
  5. }
  6. //XMLConfigBuilder也是建造者模式
  7. public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  8. try {
  9. XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
  10. return build(parser.parse());
  11. } catch (Exception e) {
  12. throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  13. } finally {
  14. ErrorContext.instance().reset();
  15. try {
  16. inputStream.close();
  17. } catch (IOException e) {
  18. // Intentionally ignore. Prefer previous error.
  19. }
  20. }
  21. }
  22. //接下来进入XMLConfigBuilder构造函数
  23. public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
  24. this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  25. }
  26. //接下来进入this后,初始化Configuration
  27. private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
  28. super(new Configuration());
  29. ErrorContext.instance().resource("SQL Mapper Configuration");
  30. this.configuration.setVariables(props);
  31. this.parsed = false;
  32. this.environment = environment;
  33. this.parser = parser;
  34. }
  35. //其中parser.parse()负责解析xml,build(configuration)创建SqlSessionFactory
  36. 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;
  10. }
  11. private void parseConfiguration(XNode root) {
  12. try {
  13. //properties 标签,用来配置参数信息,比如最常见的数据库连接信息
  14. propertiesElement(root.evalNode("properties"));
  15. Properties settings = settingsAsProperties(root.evalNode("settings"));
  16. loadCustomVfs(settings);
  17. loadCustomLogImpl(settings);
  18. //实体别名两种方式:1.指定单个实体;2.指定包
  19. typeAliasesElement(root.evalNode("typeAliases"));
  20. //插件
  21. pluginElement(root.evalNode("plugins"));
  22. //用来创建对象(数据库数据映射成java对象时)
  23. objectFactoryElement(root.evalNode("objectFactory"));
  24. objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
  25. reflectorFactoryElement(root.evalNode("reflectorFactory"));
  26. settingsElement(settings);
  27. // read it after objectFactory and objectWrapperFactory issue #631
  28. //数据库环境
  29. environmentsElement(root.evalNode("environments"));
  30. databaseIdProviderElement(root.evalNode("databaseIdProvider"));
  31. //数据库类型和Java数据类型的转换
  32. typeHandlerElement(root.evalNode("typeHandlers"));
  33. //这个是对数据库增删改查的解析
  34. mapperElement(root.evalNode("mappers"));
  35. } catch (Exception e) {
  36. throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  37. }
  38. }

总结: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. }
  36. }

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

生成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);
  3. }

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

SqlSession会话的创建过程

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

创建Transaction(两种方式)

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

获得Mapper对象

  1. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  2. public <T> T getMapper(Class<T> type) {
  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);
  3. }

从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. }
  13. public T newInstance(SqlSession sqlSession) {
  14. final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
  15. return newInstance(mapperProxy);
  16. }

这里通过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);
  5. }
  6. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

执行SQL

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);
  16. }

调用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;
  51. }

调用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. }
  11. }
  12. public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  13. try {
  14. //Configuration里的mappedStatements里根据key(id的全路径)获取MappedStatement 对象
  15. MappedStatement ms = configuration.getMappedStatement(statement);
  16. return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  17. } catch (Exception e) {
  18. throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
  19. } finally {
  20. ErrorContext.instance().reset();
  21. }
  22. }

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);
  7. }
  8. public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
  9. Cache cache = ms.getCache();
  10. if (cache != null) {
  11. flushCacheIfRequired(ms);
  12. if (ms.isUseCache() && resultHandler == null) {
  13. ensureNoOutParams(ms, boundSql);
  14. @SuppressWarnings("unchecked")
  15. List<E> list = (List<E>) tcm.getObject(cache, key);
  16. if (list == null) {
  17. list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  18. tcm.putObject(cache, key, list); // issue #578 and #116
  19. }
  20. return list;
  21. }
  22. }
  23. return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  24. }

清空本地缓存

  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;
  38. }

从数据库查询

  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;
  18. }

执行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. }
  11. }

源码总结

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

点击关注,第一时间了解华为云新鲜技术~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/165730
推荐阅读
相关标签
  

闽ICP备14008679号