Mybatis源码解析5:Mapper执行流程1

Mybatis源码解析5:Mapper执行流程1

    • 1.项目结构
    • 2. 源码分析
      • 2.1 Mapper代理 MapperProxy#invoke
      • 2.2 创建MapperMethod
        • 2.2.1 方法名称解析器ParamNameResolve
        • 2.2.2 MapperMethod#execute
      • 2.3 DefaultSqlSession
      • 2.4 CachingExecutor
      • 2.5 SimpleExecutor#doQuery
        • 获取连接对象 Connection

1.项目结构

2. 源码分析

2.1 Mapper代理 MapperProxy#invoke

当调用BlogMapper.getById(id)时,由于BlogMapper时JDK代理的,会回调MapperProxy#invoke方法

@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {try {if (Object.class.equals(method.getDeclaringClass())) {return method.invoke(this, args);} else {return cachedInvoker(method).invoke(proxy, method, args, sqlSession);}} catch (Throwable t) {throw ExceptionUtil.unwrapThrowable(t);}}

2.2 创建MapperMethod

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {this.command = new SqlCommand(config, mapperInterface, method);this.method = new MethodSignature(config, mapperInterface, method);
}public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);if (resolvedReturnType instanceof Class<?>) {this.returnType = (Class<?>) resolvedReturnType;} else if (resolvedReturnType instanceof ParameterizedType) {this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();} else {this.returnType = method.getReturnType();}this.returnsVoid = void.class.equals(this.returnType);this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();this.returnsCursor = Cursor.class.equals(this.returnType);this.returnsOptional = Optional.class.equals(this.returnType);this.mapKey = getMapKey(method);this.returnsMap = this.mapKey != null;this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);this.paramNameResolver = new ParamNameResolver(configuration, method);
}

创建MapperMethod对象,其中的方法签名MethodSignature解析了方法的信息,我们最常用的@Param注解就是在这个时候解析的–ParamNameResolver。

2.2.1 方法名称解析器ParamNameResolve

ParamNameResolver#ParamNameResolver

public ParamNameResolver(Configuration config, Method method) {final Class<?>[] paramTypes = method.getParameterTypes();final Annotation[][] paramAnnotations = method.getParameterAnnotations();final SortedMap<Integer, String> map = new TreeMap<>();int paramCount = paramAnnotations.length;// get names from @Param annotationsfor (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {if (isSpecialParameter(paramTypes[paramIndex])) {// skip special parameterscontinue;}String name = null;for (Annotation annotation : paramAnnotations[paramIndex]) {if (annotation instanceof Param) {hasParamAnnotation = true;name = ((Param) annotation).value();break;}}if (name == null) {// @Param was not specified.if (config.isUseActualParamName()) {name = getActualParamName(method, paramIndex);}if (name == null) {// use the parameter index as the name ("0", "1", ...)// gcode issue #71name = String.valueOf(map.size());}}map.put(paramIndex, name);}names = Collections.unmodifiableSortedMap(map);}
  1. 获取方法参数数组,它是一个二阶数组,一个方法多个参数,一个参数多个注解
  2. 如果有@Param注解就将hasParamAnnotation属性设置为true。并且将该参数在方法中的索引与@Param设置的别名绑定起来(key为索引,value为@Param的值)最终封装到names。以便后期对参数的名称和实际参数的值进行绑定。

ParamNameResolver#getNamedParams

public Object getNamedParams(Object[] args) {final int paramCount = names.size();if (args == null || paramCount == 0) {return null;} else if (!hasParamAnnotation && paramCount == 1) {return args[names.firstKey()];} else {final Map<String, Object> param = new ParamMap<>();int i = 0;for (Map.Entry<Integer, String> entry : names.entrySet()) {param.put(entry.getValue(), args[entry.getKey()]);// add generic param names (param1, param2, ...)final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);// ensure not to overwrite parameter named with @Paramif (!names.containsValue(genericParamName)) {param.put(genericParamName, args[entry.getKey()]);}i++;}return param;}}
  1. 参数args为Mapper接口的参数,为数组。
  2. 遍历方法names,key为索引,value为@Param的名称。最后将@Param的名称找到参数的索引,通过索引可以找到args里面对象的值。最后将他们绑定返回。这个方法返回的也就是parameterObject,后面会提到。
2.2.2 MapperMethod#execute
public Object execute(SqlSession sqlSession, Object[] args) {Object result;switch (command.getType()) {case INSERT: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.insert(command.getName(), param));break;}case UPDATE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.update(command.getName(), param));break;}case DELETE: {Object param = method.convertArgsToSqlCommandParam(args);result = rowCountResult(sqlSession.delete(command.getName(), param));break;}case SELECT: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 if (method.returnsCursor()) {result = executeForCursor(sqlSession, args);} else {Object param = method.convertArgsToSqlCommandParam(args);result = sqlSession.selectOne(command.getName(), param);if (method.returnsOptional()&& (result == null || !method.getReturnType().equals(result.getClass()))) {result = Optional.ofNullable(result);}}break;case FLUSH:result = sqlSession.flushStatements();break;default: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;}
  1. method.convertArgsToSqlCommandParam(args)调用了ParamNameResolver#getNamedParams获取到已经绑定的参数信息
  2. 目前为止,对方法的签名已经处理完毕,接下来就交给SqlSession了。result = sqlSession.selectOne(command.getName(), param)

2.3 DefaultSqlSession

  @Overridepublic <E> List<E> selectList(String statement, Object parameter) {return this.selectList(statement, parameter, RowBounds.DEFAULT);}@Overridepublic <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {try {MappedStatement ms = configuration.getMappedStatement(statement);return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);} catch (Exception e) {throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);} finally {ErrorContext.instance().reset();}}
  1. 从Configiration#mappedStatements里面取出Satement对象,然后交给执行器Executor执行
  2. 执行器是在SqlSession里面创建,这里可以对Executor代理

2.4 CachingExecutor

  @Overridepublic <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {BoundSql boundSql = ms.getBoundSql(parameterObject);CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);}
  1. BoundSql boundSql = ms.getBoundSql(parameterObject),这个方法对Sql节点进行了解析,如果是动态Sql,这里会很复杂,后面专题在讲。只需要记住,这个方法返回了原始Sql,参数值(parameterObject),参数映射关系(parameterMappings)
    在这里插入图片描述
  2. createCacheKey这个方法创建了缓存key
  @Overridepublic <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)throws SQLException {Cache cache = ms.getCache();if (cache != null) {flushCacheIfRequired(ms);if (ms.isUseCache() && resultHandler == null) {ensureNoOutParams(ms, boundSql);@SuppressWarnings("unchecked")List<E> list = (List<E>) tcm.getObject(cache, key);if (list == null) {list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);tcm.putObject(cache, key, list); // issue #578 and #116}return list;}}return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);}

如果有缓存,就从缓存里面取;没有缓存,就从数据库查询,这里是委托SimpleExecutor查询

@SuppressWarnings("unchecked")@Overridepublic <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());if (closed) {throw new ExecutorException("Executor was closed.");}if (queryStack == 0 && ms.isFlushCacheRequired()) {clearLocalCache();}List<E> list;try {queryStack++;list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;if (list != null) {handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);} else {list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);}} finally {queryStack--;}if (queryStack == 0) {for (DeferredLoad deferredLoad : deferredLoads) {deferredLoad.load();}// issue #601deferredLoads.clear();if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {// issue #482clearLocalCache();}}return list;}

这里又定义了一个localCache缓存,缓存中没有,就queryFromDatabase从数据库中查询

2.5 SimpleExecutor#doQuery

  @Overridepublic <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {Statement stmt = null;try {Configuration configuration = ms.getConfiguration();StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);stmt = prepareStatement(handler, ms.getStatementLog());return handler.query(stmt, resultHandler);} finally {closeStatement(stmt);}}
  1. 创建SatementHandler对象,这里会代理
  2. prepareStatement方法主要负责创建连接,通过ParameterHandler设置参数
  3. 通过StatementHandler执行Satement
  4. 通过ResultSetHandler处理结果集
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {this.configuration = mappedStatement.getConfiguration();this.executor = executor;this.mappedStatement = mappedStatement;this.rowBounds = rowBounds;this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();this.objectFactory = configuration.getObjectFactory();if (boundSql == null) { // issue #435, get the key before calculating the statementgenerateKeys(parameterObject);boundSql = mappedStatement.getBoundSql(parameterObject);}this.boundSql = boundSql;this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);}
获取连接对象 Connection

BaseExecutor#getConnection

protected Connection getConnection(Log statementLog) throws SQLException {Connection connection = transaction.getConnection();if (statementLog.isDebugEnabled()) {return ConnectionLogger.newInstance(connection, statementLog, queryStack);} else {return connection;}
}ConnectionLogger#invoke
@Overridepublic Object invoke(Object proxy, Method method, Object[] params)throws Throwable {try {if (Object.class.equals(method.getDeclaringClass())) {return method.invoke(this, params);}if ("prepareStatement".equals(method.getName())) {if (isDebugEnabled()) {debug(" Preparing: " + removeBreakingWhitespace((String) params[0]), true);}PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params);stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack);return stmt;} else if ("prepareCall".equals(method.getName())) {if (isDebugEnabled()) {debug(" Preparing: " + removeBreakingWhitespace((String) params[0]), true);}PreparedStatement stmt = (PreparedStatement) method.invoke(connection, params);stmt = PreparedStatementLogger.newInstance(stmt, statementLog, queryStack);return stmt;} else if ("createStatement".equals(method.getName())) {Statement stmt = (Statement) method.invoke(connection, params);stmt = StatementLogger.newInstance(stmt, statementLog, queryStack);return stmt;} else {return method.invoke(connection, params);}} catch (Throwable t) {throw ExceptionUtil.unwrapThrowable(t);}}

通过transaction获取连接对象,如果开启了日志,那么就创建代理对象,可打印日志

ManagedTransaction#openConnection

protected void openConnection() throws SQLException {if (log.isDebugEnabled()) {log.debug("Opening JDBC Connection");}connection = dataSource.getConnection();if (level != null) {connection.setTransactionIsolation(level.getLevel());}setDesiredAutoCommit(autoCommit);
}@Override
public Connection getConnection() throws SQLException {return popConnection(dataSource.getUsername(), dataSource.getPassword()).getProxyConnection();
}public PooledConnection(Connection connection, PooledDataSource dataSource) {this.hashCode = connection.hashCode();this.realConnection = connection;this.dataSource = dataSource;this.createdTimestamp = System.currentTimeMillis();this.lastUsedTimestamp = System.currentTimeMillis();this.valid = true;this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), IFACES, this);}
  1. 通过数据源的信息获取连接对象,PooledConnection对Connection对象进行代理,便于连接池对连接对象的管理,返回的是连接对象
  2. 可设置事务隔离等级

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/264844.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

AD域控环境搭建操作手册

AD域搭建 1、准备环境1.0、介绍什么是域控服务器为什么需要域域控制器的作用部署域服务器需要考虑几个方面什么是活动目录活动目录与DNS的关系 1.1、安装Windows Serve 20191.2、安装Windows101.3、安装域服务1.4、W10加入域环境1.5、OU和域用户的创建1.6、域用户安全策略1.7、…

Wireshark使用技巧

Wireshark作为网络数据软件&#xff0c;功能强大&#xff0c;本专栏介绍仅为冰山一角&#xff0c;仅仅是一个入门级别的介绍&#xff0c;大部分功能还需要在日常工作中进行挖掘。 总结Wireshark软件的使用技巧如下&#xff1a; 1.合理部署Wireshark的位置&#xff0c;从源头保障…

ArkUI Button组件

Button 1.声明button组件 Button(label?:ResourceStr) label是按钮上面显示的文字 如果不传入label 则需要在内部嵌套其他组件 内部嵌套其他组件 可以放入icon图标来构建自己想要的样式 按钮类型 按钮使用type(ButtonType.xxx)属性来设置&#xff0c;xxx的类型分为三种 1.…

导入pgsql中的保存的html数据到hive时,换行符无法被repalce

数据如图所示&#xff1a; 当我使用replace函数 \r\n 、\r 、 \n替换时。无论如何都无法替换 最终发现可以使用chr(ASCII码) 可以匹配到&#xff0c;坑我好久。 replace(replace(replace(replace(replace(bid_html_con, chr(9),),chr(10),),chr(13),),chr(160),),chr(32),)

【GIS】JDK版本升级到17后,GeoServer的图层无法通过openLayer预览

JDK版本升级到17后&#xff0c;图层无法通过openLayer预览 1. 错误图示 终端输出的错误 网页端无法显示图层&#xff0c;并且输出错误提示 2.原因猜测 估计可能是由于java17的模块化&#xff0c;Java被分成了多个独立部署和运行的模块&#xff0c;这使得Java应用能够更快…

PyTorch深度学习实战——人群计数

PyTorch深度学习实战——人群计数 0. 前言1. 人群计数1.1 基本概念1.2 CRSNet 架构 2. 使用 CSRNet 实现人群计数2.1 模型分析2.2 数据集分析2.3 模型构建与训练 相关链接 0. 前言 人群计数是指通过图像或视频分析技术&#xff0c;对给定场景中的人群数量进行估计和统计的过程…

17、类模板

17、类模板 类模板类模板的声明类模板的使用类模板的静态成员类模板的递归实例化 类模板扩展数值型的模板参数模板型成员变量模板型成员函数模板型成员类型模板型模板参数 典型模板错误嵌套依赖依赖模板参数访问成员函数模板子类模板访问基类模板类模板中的成员虚函数 类模板 …

什么是神经网络的非线性

大家好啊&#xff0c;我是董董灿。 最近在写《计算机视觉入门与调优》&#xff08;右键&#xff0c;在新窗口中打开链接&#xff09;的小册&#xff0c;其中一部分说到激活函数的时候&#xff0c;谈到了神经网络的非线性问题。 今天就一起来看看&#xff0c;为什么神经网络需…

Vue router深入学习

Vue router深入学习 一、单页应用程序介绍 1.概念 单页应用程序&#xff1a;SPA【Single Page Application】是指所有的功能都在一个html页面上实现 2.具体示例 单页应用网站&#xff1a; 网易云音乐 https://music.163.com/ 多页应用网站&#xff1a;京东 https://jd.co…

【MYSQL】单表查询

查询语法&#xff1a; select 字段&#xff08;*表示全字段&#xff09; from 数据表 【where 条件表达式】 【group by 分组字段【having 分组条件表达式】】 【order by 排序字段【asc | desc】】 例子&#xff1a; 教职工表Teacher(Tno, TName, age, sal, mgr, DNo)&#…

通过异步序列化提高图表性能 Diagramming for WPF

通过异步序列化提高图表性能 2023 年 12 月 6 日 MindFusion.Diagramming for WPF 4.0.0 添加了异步加载和保存文件的功能&#xff0c;从而提高了响应能力。 MindFusion.Diagramming for WPF 提供了一个全面的工具集&#xff0c;用于创建各种图表&#xff0c;包括组织结构图、图…

【概率方法】MCMC 之 Gibbs 采样

上一篇文章讲到&#xff0c;MCMC 中的 HM 算法&#xff0c;它可以解决拒绝采样效率低的问题&#xff0c;但是实际上&#xff0c;当维度高的时候 HM 算法还是在同时处理多个维度&#xff0c;以两个变量 x [ x , y ] \mathbf{x} [x,y] x[x,y] 来说&#xff0c;也就是同时从联合…