Mybatis的SqlSession理解(一)
SqlSession是Mybatis最重要的构建之一,可以认为Mybatis一系列的配置目的是生成类似JDBC生成的Connection对象的statement对象,这样才能与数据库开启“沟通”,通过SqlSession可以实现增删改查(当然现在更加推荐是使用Mapper接口形式)
1 .sqlsession的创建:
SqlSessionFactoryBuilder创建SqlSessionFactory openSession,sqlSession 执行增删改查
用了注解是通过org.mybatis.spring.SqlSessionFactoryBean该类创建sqlsession的,而mapper里面的每一个方法称为statement。
public void deleteUserTest() throws IOException {
// mybatis配置文件
String resource = "SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis的配置文件信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
// 通过工厂得到SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 传入id删除 用户
sqlSession.delete("test.deleteUser", 39);
//更新
sqlSession.update("test.updateUser", user);
//插入
sqlSession.insert("test.insertUser", user);
//查询
List<User> list = sqlSession.selectOne("test.findUserByName", "小明");
// 提交事务 增删改 需要commit,查询无需commit
sqlSession.commit();
// 关闭会话
sqlSession.close();
}
2.SqlSession原理
SqlSession提供select/insert/update/delete方法,在旧版本中使用使用SqlSession接口的这些方法,但是新版的Mybatis中就会建议使用Mapper接口的方法。
映射器其实就是一个动态代理对象,进入到MapperMethod的execute方法就能简单找到SqlSession的删除、更新、查询、选择方法,从底层实现来说:通过动态代理技术,让接口跑起来,之后采用命令模式,最后还是采用了SqlSession的接口方法(getMapper()方法等到Mapper)执行SQL查询(也就是说Mapper接口方法的实现底层还是采用SqlSession接口方法实现的)。
3.SqlSession重要的四个对象
1)Execute:调度执行StatementHandler、ParmmeterHandler、ResultHandler执行相应的SQL语句;
2)StatementHandler:使用数据库中Statement(PrepareStatement)执行操作,即底层是封装好了的prepareStatement;
3)ParammeterHandler:处理SQL参数;
4)ResultHandler:结果集ResultSet封装处理返回。
1 Execute执行器
execute接口有以下方法

执行器起到至关重要的作用,它是真正执行Java与数据库交互的东西,参与了整个SQL查询执行过程中。
1)主要有三种执行器:简易执行器SIMPLE(不配置就是默认执行器)、REUSE是一种重用预处理语句、BATCH批量更新、批量专用处理器

2)执行器作用:Executor会先调用StatementHandler的prepare()方法预编译SQL语句,同时设置一些基本的运行参数,然后调用StatementHandler的parameterize()方法(实际上是启用了ParameterHandler设置参数)设置参数,resultHandler再组装查询结果返回调用者完成一次查询完成预编译,简单总结起来就是即先预编译SQL语句,之后设置参数(跟JDBC的prepareStatement过程类似)最后如果有查询结果就会组装返回。
StatementHandler 接口方法
public interface StatementHandler {
//预编译SQL语句
Statement prepare(Connection connection)
throws SQLException;
//设置一些基本的运行参数
void parameterize(Statement statement)
throws SQLException;
void batch(Statement statement)
throws SQLException;
int update(Statement statement)
throws SQLException;
<E> List<E> query(Statement statement, ResultHandler resultHandler)
throws SQLException;
BoundSql getBoundSql();
ParameterHandler getParameterHandler();
}
第一:Executor通过Configuration对象中newExecutor()方法中选择相应的执行器生成
//Configuration 类
public Executor newExecutor(Transaction transaction, ExecutorType executorType, boolean autoCommit) {
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, autoCommit);
}
//最后在可以在调用真正的Executor前可以修改插件代码,执行拦截器
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
//InterceptorChain 类中pluginAll 方法:
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
第二:在执行器中StatementHandler是根据Configuration构建的
public class SimpleExecutor extends BaseExecutor {
public SimpleExecutor(Configuration configuration, Transaction transaction) {
super(configuration, transaction);
}
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
//获取StatementHandler 对象
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
//调到最后一个方法查看详细内容
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.update(stmt);
} finally {
closeStatement(stmt);
}
}
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 handler = configuration.newStatementHandler(this, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
public List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException {
return Collections.emptyList();
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection);
//设置执行参数
handler.parameterize(stmt);
return stmt;
}
}
第三:Executor会执行StatementHandler的prepare()方法进行预编译---->填入connection对象等参数---->再调用parameterize()方法设置参数---->完成预编译
//SimpleExecutor类
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
// 执行handler.prepare()预编译sql
stmt = handler.prepare(connection);
//设置执行参数
handler.parameterize(stmt);
return stmt;
}
2 StatementHanlder数据库会话器
1)作用:简单来说就是专门处理数据库会话。详细来说就是进行预编译并且调用ParameterHandler的setParameters()方法设置参数。
2)数据库会话器主要有三种:SimpleStatementHandler、PrepareStatementHandler、CallableStatementHandler,分别对应Executor的三种执行器(SIMPLE、REUSE、BATCH)
Executor的prepareStatement()方法中调用了StatementHandler的parameterize()
第一:StatementHandler的生成是由Configuration方法中newStatementHandler()方法生成的,但是正在创建的是实现了StatementHandler接口的RoutingStatementHandler对象
//Configuration
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
第二:RoutingStatementHandler的通过适配器模式找到对应(根据上下文)的StatementHandler执行的,并且有SimpleStatementHandler、PrepareStatementHandler、CallableStatementHandler,分别对应Executor的三种执行器(SIMPLE、REUSE、BATCH)
//RoutingStatementHandler
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { switch (ms.getStatementType()) {
case STATEMENT:
delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case PREPARED:
delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case CALLABLE:
delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
default:
throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
} }
PreparedStatementHandler , public class PreparedStatementHandler extends BaseStatementHandler , BaseStatementHandler implements StatementHandler
第三:在BaseStatementHandler中重写prepare()方法,instantiateStatement()方法完成预编译,之后设置一些基础配置(获取最大行数,超时)
//BaseStatementHandler
public Statement prepare(Connection connection) throws SQLException {
ErrorContext.instance().sql(boundSql.getSql());
Statement statement = null;
try {
statement = instantiateStatement(connection);
setStatementTimeout(statement);
setFetchSize(statement);
return statement;
} catch (SQLException e) {
closeStatement(statement);
throw e;
} catch (Exception e) {
closeStatement(statement);
throw new ExecutorException("Error preparing statement. Cause: " + e, e);
}
}
第四:instantiateStatement()预编译实际上也是使用了JDBC的prepareStatement()完成预编译
protected Statement instantiateStatement(Connection connection) throws SQLException {
String sql = boundSql.getSql();
if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
String[] keyColumnNames = mappedStatement.getKeyColumns();
if (keyColumnNames == null) {
return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
return connection.prepareStatement(sql, keyColumnNames);
}
} else if (mappedStatement.getResultSetType() != null) {
return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
} else {
return connection.prepareStatement(sql);
}
}
第五:在prepareStatement中重写parameterize()方法。prepare()预编译完成之后,Executor会调用parameterize()方法
public void parameterize(Statement statement) throws SQLException {
parameterHandler.setParameters((PreparedStatement) statement);
}
(3)ParameterHandler参数处理器
作用:对预编译中参数进行设置,如果有配置typeHandler,自然会对注册的typeHandler对参数进行处理
Mybatis的SqlSession理解(一)的更多相关文章
- Mybatis的SqlSession理解(二)
Mybaits加载执行该xml配置 class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, Initi ...
- SSM-MyBatis-07:Mybatis中SqlSession的insert和delete底层到底做了什么
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 先点进去看一下insert方法 用ctrl加鼠标左键点进去看 发现是一个接口SqlSession的方法,没有实 ...
- spring中的mybatis的sqlSession是如何做到线程隔离的?
项目中常常使用mybatis配合spring进行数据库操作,但是我们知道,数据的操作是要求做到线程安全的,而且按照原来的jdbc的使用方式,每次操作完成之后都要将连接关闭,但是实际使用中我们并没有这么 ...
- Mybatis的SqlSession运行原理
前言 SqlSession是Mybatis最重要的构建之一,可以简单的认为Mybatis一系列的配置目的是生成类似 JDBC生成的Connection对象的SqlSession对象,这样才能与数据库开 ...
- Mybatis 入门到理解篇
MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code, ...
- MyBatis 入门到精通(一) 了解MyBatis获取SqlSession
MyBatis是什么? MyBatis是一款一流的支持自定义SQL.存储过程和高级映射的持久化框架.MyBatis几乎消除了所有的JDBC代码,也基本不需要手工去设置参数和获取检索结果.MyBatis ...
- 项目总结2——mybatis配置的理解
之前的项目基本上都是用mongodb,以至于mysql相关的知识异常薄弱,这次连续一个半月的加班,总算是实际用到了mysql,也使自己对mysql了解的更多,对mybatis了解的更多,这里就说一说经 ...
- 从Mybatis源码理解jdk动态代理默认调用invoke方法
一.背景最近在工作之余,把开mybatis的源码看了下,决定自己手写个简单版的.实现核心的功能即可.写完之后,执行了一下,正巧在mybatis对Mapper接口的动态代理这个核心代码这边发现一个问题. ...
- 使用ThreadLocal管理Mybatis中SqlSession对象
转自http://blog.csdn.net/qq_29227939/article/details/52029065 public class MybatisUtil { private stati ...
随机推荐
- js 简易年历
html部分 <div class='calendar'> <div class="tabBox" id='nav' > <ul> <li ...
- 爬虫学习06用selenium爬取空间
用selenium爬取空间 from selenium import webdriver from lxml import etree import time pro = webdriver.Chro ...
- 论文翻译——Rapid 2D-to-3D conversion——快速2D到3D转换
https://blog.csdn.net/qq_33445835/article/details/80143598 目前想做一个关于2D转3D的项目,由于国内资料比较少而且大部分都是基于国外的研究 ...
- mysql备份与还原-mysqldump备份、mysql与source还原
以下都以在linux操作系统上的mysql为例 mysqldump备份 mysqldump实际就是将数据库中的数据转化为建库.建表和插入记录的sql语句 1.备份一个数据库 [或其中几个表],不指定表 ...
- maven执行单元测试失败后,继续生成Jacoco&Sonar报告
为保证生成单元测试覆盖 sonarqube或者jacoco与maven集成时,如果pom文件配置了sonarqube或者Jacoco的相关配置, 那么在pom文件所在目录执行mvn clean ins ...
- 13: vue项目结构搭建与开发
vue其他篇 01: vue.js安装 02: vue.js常用指令 03: vuejs 事件.模板.过滤器 目录: 1.1 初始化项目 1.2 配置API接口,模拟后台数据 1.3 项目整体结构化开 ...
- Eclipse中手动清理项目缓存,
用过Eclipse或MyEclipse的小伙伴肯定遇到过这种情况: 代码出错后,在前台访问出问题.然后把代码改好,已经检查不到错误,可是项目在前台访问还是有问题. 这个时候,可能就是Eclipse/M ...
- 浅谈k短路算法
An Old but Classic Problem 给定一个$n$个点,$m$条边的带正权有向图.给定$s$和$t$,询问$s$到$t$的所有权和为正路径中,第$k$短的长度. Notice 定义两 ...
- RPMB分区介绍【转】
本文转载自:https://blog.csdn.net/xiezhi123456/article/details/81479793 RPMB(Replay Protected Memory Block ...
- Ping 不通的原因分析
背景 简介 ping是常用的网络管理命令,ping也属于一个通信协议,是TCP/IP协议的一部分,适用于windows和linux以及unix 根据reply用来检查网络是否通畅&网络连接的速 ...