关于mybaitis

mybatis启动流程

一、首先来看看最简单的mybatis项目启动过程sql

public static void mybatisTest() throws IOException {
    String resource = "mybatis/mybatis-config.xml";
    //配置文件
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = null;
    try {
        //开启一个session
        sqlSession = sqlSessionFactory.openSession();
        //获取mapper
        JobConfigDao jobConfigDao = sqlSession.getMapper(JobConfigDao.class);
        //查询数据
        List<JobConfig> jobConfigList = jobConfigDao.listConfig();
        System.out.println(jobConfigList);
    } finally {
        if (sqlSession != null)
            sqlSession.close();
    }
}

这个过程主要是SqlSessionFactory 的建立,先获取配置信息,而后经过SqlSessionFactoryBuilder来建立SqlSessionFactory 。
build方法的核心代码是:缓存

XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); 
var5 = this.build(parser.parse());

能够看到mybatis是经过XMLConfigBuilder来解析配置文件的。来看看XMLConfigBuilder的parse方法:session

public Configuration parse() {
    //XMLConfigBuilder中有一个boolean类型parsed,来标记是否解析过配置文件,解析过以后就设置为true,防止一样的配置被重复解析
    if (this.parsed) {
        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    } else {
        this.parsed = true;
        // 解析configuration节点下的配置
        this.parseConfiguration(this.parser.evalNode("/configuration"));
        return this.configuration;
    }
}

private void parseConfiguration(XNode root) {
    try {
        this.propertiesElement(root.evalNode("properties"));
        Properties settings = this.settingsAsProperties(root.evalNode("settings"));
        this.loadCustomVfs(settings);
        this.typeAliasesElement(root.evalNode("typeAliases"));
        this.pluginElement(root.evalNode("plugins"));
        this.objectFactoryElement(root.evalNode("objectFactory"));
        this.objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
        this.reflectorFactoryElement(root.evalNode("reflectorFactory"));
        this.settingsElement(settings);
        this.environmentsElement(root.evalNode("environments"));
        this.databaseIdProviderElement(root.evalNode("databaseIdProvider"));
        this.typeHandlerElement(root.evalNode("typeHandlers"));
        // 解析mapper
        this.mapperElement(root.evalNode("mappers"));
    } catch (Exception var3) {
        throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + var3, var3);
    }
}

能够看到,在parseConfiguration方法中会将mybatis-config.xml配置下的各类属性获取出来一一解析,并映射到相关的属性上面去。mybatis

mybatis定义的接口,怎么找到实现的?

经过上面的启动过程,已经知道mybatis是经过XMLConfigBuilder来解析配置文件的,具体解析是在parseConfiguration方法的中,获取到mappers配置节点,最后一行this.mapperElement(root.evalNode("mappers"))将节点信息转交给XMLMapperBuilder来完成对mapper的解析。app

来看看XMLMapperBuilder的parse方法:ide

public void parse() {
    if (!this.configuration.isResourceLoaded(this.resource)) {
        this.configurationElement(this.parser.evalNode("/mapper"));
        this.configuration.addLoadedResource(this.resource);
        //经过命名空间绑定mapper
        this.bindMapperForNamespace();
    }

    this.parsePendingResultMaps();
    this.parsePendingCacheRefs();
    this.parsePendingStatements();
}

由于这里的重点是想知道定义的接口是怎么实现的,因此直接来看看bindMapperForNamespace方法对如何来实现mapper的绑定:ui

private void bindMapperForNamespace() {
    String namespace = this.builderAssistant.getCurrentNamespace();
    if (namespace != null) {
        Class boundType = null;

        try {
            //经过反射获取类类型
            boundType = Resources.classForName(namespace);
        } catch (ClassNotFoundException var4) {
            ;
        }

        //若是当前类尚未绑定到配置的缓存中
        if (boundType != null && !this.configuration.hasMapper(boundType)) {
            this.configuration.addLoadedResource("namespace:" + namespace);
            //经过mybatis的Configuration将mapper注册到MapperRegistry
            this.configuration.addMapper(boundType);
        }
    }
}

来看看MapperRegistry 的addMapper:this

public <T> void addMapper(Class<T> type) {
    this.mapperRegistry.addMapper(type);
}

public <T> void addMapper(Class<T> type) {
    if (type.isInterface()) {//先判断是否为接口
        if (this.hasMapper(type)) {//若是已经注册,抛出异常
            throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
        }
        boolean loadCompleted = false;
        try {
            //建立一个代理MapperProxyFactory 并将该mapper缓存到内存的Map中去
            this.knownMappers.put(type, new MapperProxyFactory(type));
            //绑定注解
            MapperAnnotationBuilder parser = new MapperAnnotationBuilder(this.config, type);
            parser.parse();
            loadCompleted = true;
        } finally {
            if (!loadCompleted) {
                this.knownMappers.remove(type);
            }

        }
    }
}

经过对上面源码的跟踪分析,终于知道,mybatis经过MapperProxyFactory为每一个接口都提供了一个代理实现,而后经过MapperRegistry将mapper注册到容器中的。spa

那么在使用的时候又是如何来获取这个mapper的呢?代理

答案是:反射加上代理

首先经过SqlSession的getMapper方法,mybatis为SqlSession提供了一个默认的实现DefaultSqlSession,DefaultSqlSession的内部属性以下:

//Configuration配置
private final Configuration configuration;
private final Executor executor;
private final boolean autoCommit;
private boolean dirty;
private List<Cursor<?>> cursorList;

DefaultSqlSession获取配置,而后配置中获取MapperRegistry,从MapperRegistry中获取到mapper代理工厂,再经过MapperProxyFactory的newInstance来建立mapper代理类MapperProxy

总结:对于Mybatis,记住几个关键的处理类:SqlSessionFactoryBuilder建立SqlSessionFactory,SqlSessionFactory中开启一个SqlSession,经过sqlSession来执行用户操做;RegisterMapper将mapper注册到容器中,经过MapperProxyFactory来建立mapper代理,mapper代理最终是经过jdk反射包中Proxy代理类来建立的。

启动时建立的SqlSessionFactory是DefaultSqlSessionFactory,DefaultSqlSessionFactory中拥有属性Configuration,Configuration是经过XMLConfigBuilder从配置文件中解析出来的各类配置信息,Configuration中有MapperRegistry,MapperRegistry中用一个final类型的Map存储了用户定义Mapper代理实现工厂MapperProxyFactory,Mapper代理实现是MapperProxy。
相关文章
相关标签/搜索