Mybatis源码分析之Mapper执行SQL过程(三)
上两篇已经讲解了SqlSessionFactory的创建和SqlSession创建过程。今天我们来分析myabtis的sql是如何一步一步走到Excutor。
还是之前的demo
public static void main(String[] args) throws Exception {
SqlSessionFactory sessionFactory = null;
String resource = "configuration.xml";
sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
SqlSession sqlSession = sessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println(userMapper.findUserById(1));
}
我们想看下基本的时序图有个大致了解

1:DefaultSqlSession获取getMapper
@Override
public T getMapper(Class type) {
return configuration.getMapper(type, this);
}
2:Configuration获取getMapper
public T getMapper(Class type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
Configuration和DefaultSqlSession什么都没有做,交给了MapperRegistry,我们看下MapperRegistry做了什么。
3:MapperRegistry获取getMapper
@SuppressWarnings("unchecked")
public T getMapper(Class type, SqlSession sqlSession) {
final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) 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);
}
}
通过knownMappers获取一个MapperProxyFactory,后然newInstance了一下,那么newInstance得到了什么东西呢?
4:MapperProxyFactory
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy mapperProxy) {
//java代理
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
通过以上的动态代理,咱们就可以方便地使用dao接口啦。到这里我们还没有看到任何执行sql有关的信息,或者说还没走到文章开始说的的Excutor, 我们看下MapperProxy代理类
MapperProxy
public class MapperProxy implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class mapperInterface;
private final Map methodCache;
public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
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);
}
private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
}
代理类交给了mapperMethod.execute进行处理,到这里我们只是看到了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 if (method.returnsCursor()) {
result = executeForCursor(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;
}
上面代码先是判断CRUD类型,然后根据类型去选择到底执行sqlSession中的哪个方法,我们现在是查询那么程序应该走到sqlSession.selectOne。
@Override
public T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
List list = this.selectList(statement, parameter);
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
@Override
public List selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
//终于看到我们要找的executor接口了
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();
}
}
我们终于看到executor类了, 调用了query方法,接下来的事情全部交给了executor处理了,
executor底层的分析已经在上一篇已经分享了。
我们代理执行sql的基本顺序是
MapperMethod.execute() --> DefaultSqlSession.selectOne --> BaseExecutor.query --> SimpleExecutor.doQuery --> SimpleStatementHandler.query --> DefaultResultSetHandler.handleResultSets(Statement stmt) 最终得到数据。
Mybatis源码分析之Mapper执行SQL过程(三)的更多相关文章
- 精尽 MyBatis 源码分析 - SqlSession 会话与 SQL 执行入口
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
- mybatis源码分析(五)------------SQL的执行过程
在对SQL的执行过程进行分析前,先看下测试demo: /** * @author chenyk * @date 2018年8月20日 */ public class GoodsDaoTest { pr ...
- Mybatis源码分析之Mapper的创建和获取
Mybatis我们一般都是和Spring一起使用的,它们是怎么融合到一起的,又各自发挥了什么作用? 就拿这个Mapper来说,我们定义了一个接口,声明了一个方法,然后对应的xml写了这个sql语句, ...
- LinqToDB 源码分析——生成与执行SQL语句
生成SQL语句的功能可以算是LinqToDB框架的最后一步.从上一章中我们可以知道处理完表达式树之后,相关生成SQL信息会被保存在一个叫SelectQuery类的实例.有了这个实例我们就可以生成对应的 ...
- Mybatis源码分析之Mapper文件解析
感觉CSDN对markdown的支持不够友好,总是伴随各种问题,很恼火! xxMapper.xml的解析主要由XMLMapperBuilder类完成,parse方法来完成解析: public void ...
- 精尽MyBatis源码分析 - 文章导读
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
- MyBatis源码分析-SQL语句执行的完整流程
MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...
- 精尽MyBatis源码分析 - SQL执行过程(二)之 StatementHandler
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
- 精尽MyBatis源码分析 - MyBatis 的 SQL 执行过程(一)之 Executor
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
随机推荐
- OPTIMIZE TABLE ipc_analysisdatasyn, ipc_analysisdatatkv,ipc_autoupdateset, ipc_equipmentwaring,ipc_fguid, ipc_receivedata, ipc_senddata, tb_qualitativeanalysis, tb_quantifyresult, tb_quantifyresulthis
OPTIMIZE TABLE ipc_analysisdatasyn, ipc_analysisdatatkv,ipc_autoupdateset, ipc_equipmentwaring,ipc_f ...
- java 对mongodb的操作
java 对mongodb的操作 1.1连单台mongodb Mongo mg = newMongo();//默认连本机127.0.0.1 端口为27017 Mongo mg = newMongo( ...
- Java Calendar,Date,DateFormat,TimeZone,Locale等时间相关内容的认知和使用(4) DateFormat
本章主要介绍DateFormat. DateFormat 介绍 DateFormat 的作用是 格式化并解析“日期/时间”.实际上,它是Date的格式化工具,它能帮助我们格式化Date,进而将Date ...
- C#编程(十九)----------部分类
部分类 C#中使用关键字partial把类,结构或结构放在多个文件中.一般情况下,一个类全部驻留在单个文件中.但有时候,多个开发人员需要访问同一个类,或者某种类型的代码生成器生成了一个类的某部分,所以 ...
- Maven 构建
最近在工作中越来越经常的用到了Maven作为项目管理和Jar包管理和构建的工具,感觉Maven的确是很好用的.而且要将Maven的功能最大发挥出来,多模块是一个很好的集成例子. 一个Maven项目包括 ...
- java中Double类数字太大时页面正常显示而不要用科学计数法
/** * 当浮点型数据位数超过10位之后,数据变成科学计数法显示.用此方法可以使其正常显示. * @param value * @return Sting */ public static Stri ...
- 【Centos】centos查看磁盘使用情况
1.查看分区和磁盘 lsblk 查看分区和磁盘 2.查看空间使用情况 df -h 查看空间使用情况 3.分区工具查看分区信息 fdisk -l 分区工具查看分区信息 4.查看分区 cfdisk /de ...
- ASP.NET MVC:Cookie 的过期时间在服务器端是获取不到的
现状 一旦 Cookie 在服务器端设置后,在后续的请求中是获取不到过期时间的,因为:Cookie 是存储和过期处理都是由客户端管理的,在后续的请求中,浏览器向服务器发送 Cookie 的时候就不包含 ...
- python测试开发django-43.session机制(登录/注销)
前言 当我们登录访问一个网站时,服务器需要识别到你已经登录了,才有相应的权限访问登录之后的页面.用户退出登录后,将无权限访问再访问登录后的页面. 从登录到退出的一整个流程,可以看成是与服务器的一次会话 ...
- 解决appcompat中各种奇葩的错误
一.依赖/脱离appcompat 在新版本中Google跟新了一个依赖包,这个包包含了v4和v7的东西(v7是要依赖v4这个包的,所以用到v7时必须用一起的v4),只要你的编译版本compile wi ...