4、Mybatis 執行流程全解析

知識點: 執行流程解析 Mybatis 插件開發java

1、執行流程解析

1. 配置文件解析 configuration

理解解析流程以前先回顧一下mybatis中配置文件的結構:sql

mybatis-config.xml

<configuration>
  <properties/>
  <settting/>
  <typeHandlers/>
  <..../>
  <mappers/>
</configuration>
複製代碼

mybatis-mapper.xml

<mapper >
  <cache/>
  <resultMap/>
  <select/> 
  <update/> 
  <delete/> 
  <insert/> 
</mapper>
複製代碼

配置文件的解析流程便是將上述XML描述元素轉換成對應的Java對象過程,其最終轉換對象及其關係以下圖: apache

配置元素解析構建器

>org.apache.ibatis.builder.xml.XMLConfigBuilder
 >org.apache.ibatis.builder.xml.XMLMapperBuilder
  >org.apache.ibatis.builder.xml.XMLStatementBuilder
   >org.apache.ibatis.builder.SqlSourceBuilder
    >org.apache.ibatis.scripting.xmltags.XMLScriptBuilder
 >org.apache.ibatis.builder.annotation.MapperAnnotationBuilder
複製代碼

sql statement 構建流程源碼

>org.apache.ibatis.session.SqlSessionFactoryBuilder#build()
//1.Config.xml 文件解析
>org.apache.ibatis.builder.xml.XMLConfigBuilder#parse
 >org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration
  >org.apache.ibatis.builder.xml.XMLConfigBuilder#mapperElement
//2.Mapper.xml 文件解析
>org.apache.ibatis.builder.xml.XMLMapperBuilder#parse 
 >org.apache.ibatis.builder.xml.XMLMapperBuilder#configurationElement
  >org.apache.ibatis.builder.xml.XMLMapperBuilder#buildStatementFromContext(java.util.List<org.apache.ibatis.parsing.XNode>)
//3.Statemen sql塊解析
>org.apache.ibatis.builder.xml.XMLStatementBuilder#parseStatementNode
 >org.apache.ibatis.builder.MapperBuilderAssistant#addMappedStatement
// 4.動態SQL腳本解析
>org.apache.ibatis.scripting.xmltags.XMLLanguageDriver#createSqlSource()
>org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode()
>org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseDynamicTags() 
複製代碼

2. 會話建立SqlSession

首先咱們仍是先來了解一下會話對像的組成結構以下圖: bash

會話構建源碼解析

>org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSession(boolean)
 >org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSessionFromDataSource
  >org.apache.ibatis.transaction.TransactionFactory#newTransaction
  >org.apache.ibatis.session.Configuration#newExecutor
   >org.apache.ibatis.executor.SimpleExecutor
   >org.apache.ibatis.executor.CachingExecutor
     //執行器插件包裝
   >org.apache.ibatis.plugin.InterceptorChain#pluginAll(executor)
  >org.apache.ibatis.session.defaults.DefaultSqlSession#DefaultSqlSession() 
複製代碼

3. 方法執行 StatementHandler

StatementHandler 源碼解析

>org.apache.ibatis.session.defaults.DefaultSqlSession#selectList()
 >org.apache.ibatis.executor.CachingExecutor#query()
  >org.apache.ibatis.executor.BaseExecutor#query()
   >org.apache.ibatis.executor.BaseExecutor#queryFromDatabase
>org.apache.ibatis.session.Configuration#newStatementHandler
org.apache.ibatis.executor.statement.BaseStatementHandler#BaseStatementHandler
org.apache.ibatis.session.Configuration#newParameterHandler
org.apache.ibatis.plugin.InterceptorChain#pluginAll(parameterHandler)
org.apache.ibatis.session.Configuration#newResultSetHandler
org.apache.ibatis.plugin.InterceptorChain#pluginAll(resultSetHandler)
>org.apache.ibatis.plugin.InterceptorChain#pluginAll(statementHandler)
>org.apache.ibatis.executor.BaseExecutor#getConnection
>org.apache.ibatis.executor.statement.PreparedStatementHandler#instantiateStatement
>org.apache.ibatis.executor.statement.PreparedStatementHandler#parameterize
>org.apache.ibatis.scripting.defaults.DefaultParameterHandler#setParameters
org.apache.ibatis.type.BaseTypeHandler#setParameter
org.apache.ibatis.type.UnknownTypeHandler#setNonNullParameter
org.apache.ibatis.type.IntegerTypeHandler#setNonNullParameter
複製代碼

2、myBatis插件開發

插件的四大擴展點session

  1. Executor
  2. StatementHandler
  3. ParameterHandler
  4. ResultSetHandler

分頁插件實現: 用戶在接口中聲明Page 對像實現後,由插件實現自動分頁。使用示例以下:mybatis

public class Page implements java.io.Serializable {
   private int szie; // 每頁大
   private int number; // 當前頁碼
}
複製代碼

page參數聲明app

@Select("select * from user")
List<User> selectByPage(String name, Page page);
複製代碼

客戶端調用ide

mapper.selectByPage("小明", new Page(3, 2))

select * from user  limit 10,20
複製代碼

實現目標分解ui

  1. 修改 修改SQL 並添加 limit 語句
  2. 判斷方法參數中是否有Page對象
  3. 取出Page對象 生成limit 語句
  4. 上述操做必須在PreparedStatement 對像生成前完成

完整代碼以下:this

package com.niuh.mybatis.dao;

import com.sun.deploy.util.ReflectionUtil;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
/**
 * @author: hejianhui
 * @create: 2019-07-13 10:48
 * @see PagePlugin
 * @since JDK1.8
 */
public class PagePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return null;
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof StatementHandler) {
            return Proxy.newProxyInstance(PagePlugin.class.getClassLoader(),
                    new Class[]{StatementHandler.class},
                    new PageHandler((StatementHandler) target));
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }


    private class PageHandler implements InvocationHandler {
        StatementHandler handler;

        public PageHandler(StatementHandler handler) {
            this.handler = handler;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equalsIgnoreCase("prepare")) {
                setParametersProxy();
            }
            return method.invoke(handler, args);
        }

        private void setParametersProxy() {
            if (handler.getBoundSql().getParameterObject() instanceof Map) {
                ((Map) handler.getBoundSql().getParameterObject()).values().stream()
                        .filter(a -> a instanceof Page)
                        .findFirst()
                        .ifPresent(
                                page -> {
                                    appendPageSql((Page) page);
                                }
                        );
            }
        }

        private void appendPageSql(Page page) {
            try {
                BoundSql sql = handler.getBoundSql();
                sql.getSql();
                String limit = String.format(" limit %s,%s", page.getBegin(), page.getSzie());
                setFileValue("sql", sql, sql.getSql() + limit);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    private Object getFileValue(String fileName, Object target) throws NoSuchFieldException, IllegalAccessException {
        Field sqlField = target.getClass().getDeclaredField(fileName);
        sqlField.setAccessible(true);
        return sqlField.get(target);
    }

    private Object setFileValue(String fileName, Object target, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field sqlField = target.getClass().getDeclaredField(fileName);
        sqlField.setAccessible(true);
        sqlField.set(target, value);
        return sqlField.get(target);
    }
}
複製代碼
相關文章
相關標籤/搜索