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理解(一)的更多相关文章

  1. Mybatis的SqlSession理解(二)

    Mybaits加载执行该xml配置 class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, Initi ...

  2. SSM-MyBatis-07:Mybatis中SqlSession的insert和delete底层到底做了什么

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 先点进去看一下insert方法 用ctrl加鼠标左键点进去看 发现是一个接口SqlSession的方法,没有实 ...

  3. spring中的mybatis的sqlSession是如何做到线程隔离的?

    项目中常常使用mybatis配合spring进行数据库操作,但是我们知道,数据的操作是要求做到线程安全的,而且按照原来的jdbc的使用方式,每次操作完成之后都要将连接关闭,但是实际使用中我们并没有这么 ...

  4. Mybatis的SqlSession运行原理

    前言 SqlSession是Mybatis最重要的构建之一,可以简单的认为Mybatis一系列的配置目的是生成类似 JDBC生成的Connection对象的SqlSession对象,这样才能与数据库开 ...

  5. Mybatis 入门到理解篇

    MyBatis         MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code, ...

  6. MyBatis 入门到精通(一) 了解MyBatis获取SqlSession

    MyBatis是什么? MyBatis是一款一流的支持自定义SQL.存储过程和高级映射的持久化框架.MyBatis几乎消除了所有的JDBC代码,也基本不需要手工去设置参数和获取检索结果.MyBatis ...

  7. 项目总结2——mybatis配置的理解

    之前的项目基本上都是用mongodb,以至于mysql相关的知识异常薄弱,这次连续一个半月的加班,总算是实际用到了mysql,也使自己对mysql了解的更多,对mybatis了解的更多,这里就说一说经 ...

  8. 从Mybatis源码理解jdk动态代理默认调用invoke方法

    一.背景最近在工作之余,把开mybatis的源码看了下,决定自己手写个简单版的.实现核心的功能即可.写完之后,执行了一下,正巧在mybatis对Mapper接口的动态代理这个核心代码这边发现一个问题. ...

  9. 使用ThreadLocal管理Mybatis中SqlSession对象

    转自http://blog.csdn.net/qq_29227939/article/details/52029065 public class MybatisUtil { private stati ...

随机推荐

  1. 大数据自学3-Windows客户端DbVisualizer/SQuirreL配置连接hive

    前面已经学习了将数据从Sql Server导入到Hive DB,并在Hue的Web界面可以查询,接下来是配置客户端工具直接连Hive数据库,常用的有DbVisualizer.SQuirreL SQL ...

  2. sql server 触发器的简单用法

    触发器  -- 一下写的都是我对触发器的理解 当在执行insert . delete . 等操作的时候 随便要做一些额外的操作, 比如在添加的时候就会将新添加的数据存到inserted表中 写个实例 ...

  3. javaweb笔记—01(编程英语、常识、Tomcat配置问题)

    第一部分: 编程英语: legal:adj. 法律的:合法的:法定的 Userful :出版商  sponsor: n. 赞助者:主办者:保证人 | vt. 赞助:发起 essential:n. 本质 ...

  4. nginx的gzip压缩功能

    我们在开发网站的时候,应该要考虑到pv,因为pv比较大可能会造成服务器带宽不够用,进而导致用户体验变差. 这个时候我们就可以考虑用nginx的gzip功能. 在nginx中开启gzip压缩功能很简单, ...

  5. 从percona server 5.7换到mariadb 10.2

    过去两年半一直推荐使用percona server,今天开始,因为一些mysql迟迟不不愿意支持的特性,打算换回mariadb 10.2了,具体哪些不说了,总之非常关键,mariadb都支持一两年了, ...

  6. c++ linux下输出中文

    同样,使用的是VS FOR LINUX进行测试. converting to execution character set: Invalid or incomplete multibyte or w ...

  7. 【题解】Luogu P3871 [TJOI2010]中位数

    平衡树板题 原题传送门 这道题要用Splay,我博客里有对Splay的详细介绍 每次加入一个数,把数插入平衡树中 并且要记录一共有多少个数 每次查询就查询平衡树中第(总数-1)/2+1个数 十分暴力 ...

  8. k8s device plugin

    基本概念入门: Device Manager Proposal Device plugin offical Doc(中文) device-plugins offical Doc(En) Go thro ...

  9. 接口自动化(unittest)

    一.用例 TestCase 也就是测试用例 TestSuite 多个测试用例集合在一起,就是TestSuite TestLoader是用来加载TestCase到TestSuite中的 TestRunn ...

  10. Codeforces Round #425 (Div. 2) Problem A Sasha and Sticks (Codeforces 832A)

    It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day h ...