一、传统的jdbc操作步骤

  • 获取驱动
  • 获取jdbc连接
  • 创建参数化预编译的sql
  • 绑定参数
  • 发送sql到数据库执行
  • 将将获取到的结果集返回应用
  • 关闭连接

传统的jdbc代码:

package com.zjp;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;public class JDBCTest {public static void main(String[] args) {try {Connection con = null; //定义一个MYSQL链接对象Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL驱动con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true", "root", "root"); //链接本地MYSQL//更新一条数据String updateSql = "UPDATE user_t SET user_name = 'test' WHERE id = ?";PreparedStatement pstmt = con.prepareStatement(updateSql);pstmt.setString(1, "1");long updateRes = pstmt.executeUpdate();System.out.print("UPDATE:" + updateRes);//查询数据并输出String sql = "select * from user_t where id = ?";PreparedStatement pstmt2 = con.prepareStatement(sql);pstmt2.setString(1, "1");ResultSet rs = pstmt2.executeQuery();while (rs.next()) { //循环输出结果集String id = rs.getString("id");String username = rs.getString("user_name");System.out.print("\r\n\r\n");System.out.print("id:" + id + ",username:" + username);}//关闭资源rs.close();pstmt.close();pstmt2.close();con.close();} catch (Exception e) {e.printStackTrace();}}
}

二、mybatis 执行sql

mybatis要执行sql,同样也需要获取到数据库连接,这个在mybatis里面就是sqlSession

// 使用MyBatis提供的Resources类加载mybatis的配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 构建sqlSession的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();

2.1 获取mapper对象

获取到了session对象之后就是获取mapper对象了,在mybatis中是使用动态代理的方式获取

 @Overridepublic <T> T getMapper(Class<T> type) {//最后会去调用MapperRegistry.getMapperreturn configuration.<T>getMapper(type, this);}
 /*** 返回代理类* @param type* @param sqlSession* @return*/@SuppressWarnings("unchecked")public <T> T getMapper(Class<T> type, SqlSession sqlSession) {// MapperProxyFactory去把代理类做出来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);}}
@SuppressWarnings("unchecked")protected T newInstance(MapperProxy<T> mapperProxy) {//用JDK自带的动态代理生成映射器return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);}public T newInstance(SqlSession sqlSession) {final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);return newInstance(mapperProxy);}
  • 通过session获取mapper,session通过MapperProxyFactory代理对象去获取mapper对象,最终在newInstance中我们看到了使用jdk自带的动态代理方式获取到了mapper对象。

2.2 执行sql语句

现在获取到了mapper对象,那么下一步就是执行sql语句了。

@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//代理以后,所有Mapper的方法调用时,都会调用这个invoke方法//并不是任何一个方法都需要执行调用代理对象进行执行,如果这个方法是Object中通用的方法(toString、hashCode等)无需执行if (Object.class.equals(method.getDeclaringClass())) {try {return method.invoke(this, args);} catch (Throwable t) {throw ExceptionUtil.unwrapThrowable(t);}}//这里优化了,去缓存中找MapperMethodfinal MapperMethod mapperMethod = cachedMapperMethod(method);//执行 sqlreturn mapperMethod.execute(sqlSession, args);}

所有的sql语句都会调用invoke方法,会后都要调用execute来执行sql语句

public Object execute(SqlSession sqlSession, Object[] args) {Object result;//可以看到执行时就是4种情况,insert|update|delete|select,分别调用SqlSession的4大类方法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()) {//如果结果是mapresult = executeForMap(sqlSession, args);} else {//否则就是一条记录Object param = method.convertArgsToSqlCommandParam(args);result = sqlSession.selectOne(command.getName(), param);}} 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;}

这个方法也就是通过使用枚举的方式执行insert|update|delete|select,分别执行不同的方法。这里跟着select,这个也是最复杂的。在这里我们看到了很重要的一个方法

result = sqlSession.selectOne(command.getName(), param);

通过源码可知selectOne方法转而去调用selectList,很简单的,如果得到0条则返回null,得到1条则返回1条,得到多条报TooManyResultsException错,特别需要主要的是当没有查询到结果的时候就会返回null。因此一般建议在mapper中编写resultType的时候使用包装类型而不是基本类型,比如推荐使用Integer而不是int。这样就可以避免NPE

 //核心selectOne@Overridepublic <T> T selectOne(String statement, Object parameter) {// Popular vote was to return null on 0 results and throw exception on too many.List<T> list = this.<T>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;}}
 public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {try {//根据statement id找到对应的MappedStatementMappedStatement ms = configuration.getMappedStatement(statement);//转而用执行器来查询结果,注意这里传入的ResultHandler是nullreturn 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();}}

从selectList方法中可以看出来,最终的查询还是交给了executor

public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {//得到绑定sqlBoundSql boundSql = ms.getBoundSql(parameter);//创建缓存KeyCacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);//查询return query(ms, parameter, rowBounds, resultHandler, key, boundSql);}

从MappedStatement对象中获取到BoundSql对象,BoundSql对象包含了我们需要执行的sql语句。

public <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//这里看到ResultHandler传入了StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);//准备语句stmt = prepareStatement(handler, ms.getStatementLog());//StatementHandler.queryreturn handler.<E>query(stmt, resultHandler);} finally {closeStatement(stmt);}}

通过一些列的跟踪,定位到了doQuery方法,最终sql语句的执行交给了StatementHandler对象,这个对象也就是我们最常用的,封装的是PreparedStatement

 @Overridepublic <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {PreparedStatement ps = (PreparedStatement) statement;ps.execute();// 结果交给了ResultSetHandler 去处理return resultSetHandler.<E> handleResultSets(ps);}

很明显这里就是使用的PreparedStatement进行处理。

public List<Object> handleResultSets(Statement stmt) throws SQLException {ErrorContext.instance().activity("handling results").object(mappedStatement.getId());final List<Object> multipleResults = new ArrayList<Object>();int resultSetCount = 0;ResultSetWrapper rsw = getFirstResultSet(stmt);List<ResultMap> resultMaps = mappedStatement.getResultMaps();//一般resultMaps里只有一个元素int resultMapCount = resultMaps.size();validateResultMapsCount(rsw, resultMapCount);while (rsw != null && resultMapCount > resultSetCount) {ResultMap resultMap = resultMaps.get(resultSetCount);handleResultSet(rsw, resultMap, multipleResults, null);rsw = getNextResultSet(stmt);cleanUpAfterHandlingResultSet();resultSetCount++;}String[] resultSets = mappedStatement.getResulSets();if (resultSets != null) {while (rsw != null && resultSetCount < resultSets.length) {ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);if (parentMapping != null) {String nestedResultMapId = parentMapping.getNestedResultMapId();ResultMap resultMap = configuration.getResultMap(nestedResultMapId);handleResultSet(rsw, resultMap, null, parentMapping);}rsw = getNextResultSet(stmt);cleanUpAfterHandlingResultSet();resultSetCount++;}}return collapseSingleResultList(multipleResults);}

最后就是返回结果集了。

Mybatis源码解析-sql执行相关推荐

  1. 3.MyBatis源码解析-CRUD执行流程--阿呆中二

    CRUD执行流程 MyBatis CRUD执行流程 与我联系 MyBatis 本文是对mybatis 3.x源码深度解析与最佳实践学习的总结,包括XML文件解析流程.SqlSession构建流程.CR ...

  2. mybatis一个方法执行多条sql_精尽MyBatis源码分析——SQL执行过程之Executor!

    MyBatis的SQL执行过程 在前面一系列的文档中,我已经分析了 MyBatis 的基础支持层以及整个的初始化过程,此时 MyBatis 已经处于就绪状态了,等待使用者发号施令了 那么接下来我们来看 ...

  3. MyBatis 源码分析 - SQL 的执行过程

    本文速览 本篇文章较为详细的介绍了 MyBatis 执行 SQL 的过程.该过程本身比较复杂,牵涉到的技术点比较多.包括但不限于 Mapper 接口代理类的生成.接口方法的解析.SQL 语句的解析.运 ...

  4. 【MyBatis源码解析】MyBatis一二级缓存

    MyBatis缓存 我们知道,频繁的数据库操作是非常耗费性能的(主要是因为对于DB而言,数据是持久化在磁盘中的,因此查询操作需要通过IO,IO操作速度相比内存操作速度慢了好几个量级),尤其是对于一些相 ...

  5. mybatis源码解析(一)

    Mybatis 源码解析 (一) 一. ORM框架的作用 实际开发系统时,我们可通过JDBC完成多种数据库操作.这里以传统JDBC编程过程中的查询操作为例进行说明,其主要步骤如下: (1)注册数据库驱 ...

  6. Mybatis源码解析《二》

    导语 在前一篇文章Mybatis源码解析<一>中,已经简单了捋了一下mybatis核心文件和mapper配置文件的一个基本的解析流程,这是理解mybatis的基本,和spring中的配置文 ...

  7. 对标阿里P8的MyBatis源码解析文档,面试/涨薪两不误,已献出膝盖

    移动互联网的特点是大数据.高并发,对服务器往往要求分布式.高性能.高灵活等,而传统模式的Java数据库编程框架已经不再适用了. 在这样的背景下,一个Java的持久框架MyBatis走入了我们的世界,它 ...

  8. Mybatis源码解析(一):环境搭建

    Mybatis源码系列文章 手写源码(了解源码整体流程及重要组件) Mybatis源码解析(一):环境搭建 Mybatis源码解析(二):全局配置文件的解析 Mybatis源码解析(三):映射配置文件 ...

  9. 【Flink】 Flink 源码之 SQL 执行流程

    1.概述 转载:Flink 源码之 SQL 执行流程 2.前言 本篇为大家带来Flink执行SQL流程的分析.它的执行步骤概括起来包含: 解析.使用Calcite的解析器,解析SQL为语法树(SqlN ...

最新文章

  1. 堆和栈组合:双端队列c++
  2. android 如何保留数据两位小数
  3. R语言编程艺术(3)R语言编程基础
  4. 计算机统考测试,计算机统考专业测试题.doc
  5. 【Kafka】Kafka Consumer 管理 Offset 原理
  6. WebSphere 管理员界面 修改配置之后,没有反应的原因,需要按下[保存]link
  7. 强烈推荐!mac超牛皮解压/压缩工具MyZip 1.1.2 mac免费版
  8. 空间apiLinux系统调用及用户编程接口(API)学习
  9. 微信公众平台开发(51)会员卡
  10. 【渝粤题库】陕西师范大学201461 司法文书写作作业(高起专)
  11. 每秒浮点运算次数FLOPS
  12. 特殊符号大全复制_特殊符号大全爱好者工具讲解
  13. 计算机键盘功能键介绍6,笔记本全部按键功能的详细说明笔记本电脑键盘上有什么区别...
  14. 8box播放器的引用
  15. 深度终端:ubuntu等linux下好用的远程终端软件
  16. python 调用scp命令 实践
  17. 数据结构(c语言版 第二版 严蔚敏)第一张绪论笔记
  18. sans用计算机演奏有歌词儿,Sans toi歌词 Joyce Jonathan、曲婉婷_晴格歌词网
  19. 卡巴斯基公布财报,2020年业务稳定增长
  20. Clion + mysql (win/Mac + 本地/远程)

热门文章

  1. ESP8266 如何修改默认上电校准方式?另外为什么 ESP8266 进⼊启动模式(2,7)并触发看⻔狗复位?
  2. java窗体设置最小宽度_flex web Application设置最小高度和宽度。
  3. python关键字匹配_python通过BF算法实现关键词匹配的方法
  4. Android SQLite开发调试工具 Android Debug Database
  5. 全志 修改KEY Patch
  6. 服务降级和服务熔断的区别_Spring Cloud 熔断 隔离 服务降级
  7. JDBC-Mysql-编译预处理(占位符)
  8. [文章备份]源代码制图工具Understand最新可用注册码
  9. Luogu1574 超级数
  10. Spring+SpringMVC +MyBatis整合配置文件案例66666