美文网首页
mybatis源码分析-mapper对象动态代理

mybatis源码分析-mapper对象动态代理

作者: cjxz | 来源:发表于2018-12-25 17:54 被阅读0次
        public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
            try {
                //将输入流转换成XMLConfigBuilder对象。然后调用parse方法解析。最后采用默认的SqlSessionFactory来返回
                XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
                //XMLConfigBuilder.parse()将XML转换成了configuration对象。然后直接new一个DefaultSqlSessionFactory对象
                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);
        }
    
    • 将XML转换成configuration对象
    • new DefaultSqlSessionFactory,将得到的configuration对象作为属性赋给DefaultSqlSessionFactory
        public DefaultSqlSessionFactory(Configuration configuration) {
            this.configuration = configuration;
        }
        private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
            Transaction tx = null;
            try {
                final Environment environment = configuration.getEnvironment();
                final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
                tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
                final Executor executor = configuration.newExecutor(tx, execType);
                return new DefaultSqlSession(configuration, executor, autoCommit);
            } catch (Exception e) {
                closeTransaction(tx); // may have fetched a connection so lets call close()
                throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
            } finally {
                ErrorContext.instance().reset();
            }
        }
    

    当调用sqlSessionFactory.openSession()获得一个sqlSession时,调用的就是上面的方法。从transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);里面获得事务对象Transaction。从Configuration对象里面获得Executor对象

        public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
            executorType = executorType == null ? defaultExecutorType : executorType;
            executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
            Executor executor;
            if (ExecutorType.BATCH == executorType) {
                executor = new BatchExecutor(this, transaction);
            } else if (ExecutorType.REUSE == executorType) {
                executor = new ReuseExecutor(this, transaction);
            } else {
                //默认走的这个逻辑
                executor = new SimpleExecutor(this, transaction);
            }
            if (cacheEnabled) {
                executor = new CachingExecutor(executor);
            }
            executor = (Executor) interceptorChain.pluginAll(executor);
            return executor;
        }
    

    默认情况下使用SimpleExecutor对象作为执行器

        public SimpleExecutor(Configuration configuration, Transaction transaction) {
            super(configuration, transaction);
        }
    

    接下来使用getMapper方法获得一个接口的代理类

        @Override
        public <T> T getMapper(Class<T> type) {
            return configuration.<T>getMapper(type, this);
        }
        //Configuration类
        public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
            return mapperRegistry.getMapper(type, sqlSession);
        }
    
    • 1.使用SqlSession调用getMapper()方法获得Mapper对象。
    • 2.调用MapperRegistry里面的getMapper()
      • 在解析xml文件的时候就已经处理了<mappers>标签。使用XMLMapperBuilder类解析的时候有一个方法parse()进行处理。会将所有的mapper注册到MapperRegistry里面。代码逻辑如下。实现方式很简单就是将mapper标签里面的namespace属性添加到集合里面
        public void parse() {
            if (!configuration.isResourceLoaded(resource)) {
                //<mapper namespace="org.apache.ibatis.domain.blog.mappers.AuthorMapper"></mapper>
                //解析mapper节点
                configurationElement(parser.evalNode("/mapper"));
                configuration.addLoadedResource(resource);
                //这里就是绑定mapper和class的地方
                bindMapperForNamespace();
            }
    
            parsePendingResultMaps();
            parsePendingChacheRefs();
            parsePendingStatements();
        }
        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);
                    }
                }
            }
        }    
    
    • 3.通过前面注册了class的全路径,使用mapperProxyFactory来创建mapper接口实现类。这里的mapperProxyFactory会为每一个mapper都对应一个mapperProxyFactory。因为configuration.addMapper(boundType);里面使用map接口为每一个mapper都创建了一个工厂
        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 {
                    //每次都new一个新的MapperProxyFactory放到map中
                    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
        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);
            }
        }
    
    • 4.最后通过JDK的动态代理创建一个代理类交给开发者使用
    
        //MapperProxyFactory
        public T newInstance(SqlSession sqlSession) {
            final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
            return newInstance(mapperProxy);
        }
        protected T newInstance(MapperProxy<T> mapperProxy) {
            return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
        }
    
    • 5.开发者使用接口调用方法会执行代理类MapperProxy对象里面的invoke方法。调用invoke方法有点小巧妙。代码如下:
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (Object.class.equals(method.getDeclaringClass())) {
                try {
                    return method.invoke(this, args);
                } catch (Throwable t) {
                    throw ExceptionUtil.unwrapThrowable(t);
                }
            }
            final MapperMethod mapperMethod = cachedMapperMethod(method);
            return mapperMethod.execute(sqlSession, args);
        }
    

    上面代码中可以看到如果是执行Object类的方式那么直接调用method.invoke。如果不是Object的方法,那么执行的是MapperMethod方法。我们知道一个接口没有实现是不能够被实例化的,并且我们在写接口时,确实没有给任何实现,那么Mybatis是怎么帮我们做事的呢?就是上面这段代码。首先通过代理类生成代理对象。当执行接口中的方法时,都是调用这个invoke方法,当你不是调用Object下面的方法,那么统一都执行MapperMethod方法来执行。

        private MapperMethod cachedMapperMethod(Method method) {
            MapperMethod mapperMethod = methodCache.get(method);
            if (mapperMethod == null) {
                //mapperInterface:表示调用接口,也就是mapper标签上面的namespace
                //method:方法名称,也就是mapper文件里面的<select|insert|update|delete id="methodName">具体语句的id
                //configuration对象。因为所有的配置文件最终都放到了configuration,所以再查询使用的参数,查询之后的返回值类型等数据TypeHandler等等都在configuration里面
                mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
                methodCache.put(method, mapperMethod);
            }
            return mapperMethod;
        }
    

    mapperMethod持有接口名,方法名,configuration。而接口名对应mapper标签的namespace;方法名对应<select id="method">里面的id。configuration持有所有配置信息例如TypeHandler,TypeAlias等等。然后调用execute()方法执行

        public Object execute(SqlSession sqlSession, Object[] args) {
            Object result;
            if (SqlCommandType.INSERT == command.getType()) {
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(sqlSession.insert(command.getName(), param));
            } else if (SqlCommandType.UPDATE == command.getType()) {
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(sqlSession.update(command.getName(), param));
            } else if (SqlCommandType.DELETE == command.getType()) {
                Object param = method.convertArgsToSqlCommandParam(args);
                result = rowCountResult(sqlSession.delete(command.getName(), param));
            } else if (SqlCommandType.SELECT == command.getType()) {
                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 {
                    Object param = method.convertArgsToSqlCommandParam(args);
                    result = sqlSession.selectOne(command.getName(), param);
                }
            } else if (SqlCommandType.FLUSH == command.getType()) {
                result = sqlSession.flushStatements();
            } else {
                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;
        }
    

    从上面的代码可以看出所有的所有的mapper对象实际都是MapperMethod对象,然后MapperMethod持有方法名『全类名.方法名』还有执行的操作『select;update;insert;delete』还有sql的各种参数方法签名。然后执行sql语句

    相关文章

      网友评论

          本文标题:mybatis源码分析-mapper对象动态代理

          本文链接:https://www.haomeiwen.com/subject/cwxqlqtx.html