Mybaits加载执行该xml配置

class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean

spring 在初始化 sqlsessionbean的时候通过createBean调用了在SqlSessionFactoryBean中实现了接口InitializingBean的afterPropertiesSet()方法在该方法中调用了buildSqlSessionFactory()开始创建SqlSessionFactory

buildSqlSessionFactory()方法完成以下功能

一:

a)    创建configuration

b)    typeAliasesPackage

c)    typeAliases TYPE_ALIASES将类型存放到此map里面同b

d)    plugins configuration添加插件

e)    typeHandlersPackage

f)    typeHandlers

g)    xmlConfigBuilder.parse()将所有的配置从xml中读取并放入到对应的变量里面

h)    mapperLocations

二:xmlMapperBuilder.parse()——> configurationElement

a)    parameterMapElement(context.evalNodes("/mapper/parameterMap"));将mapper.xml中的prameterMap节点的数据添加到configuration.parameterMaps中

b)    resultMapElements(context.evalNodes("/mapper/resultMap"));将mapper.xml中的resultMap节点的数据添加到configuration.incompleteResultMaps中

c)    sqlElement(context.evalNodes("/mapper/sql"));

d)    buildStatementFromContext(select|insert|update|delete);buildStatementFromContext:从mapper 中获取sql语句,执行类型(增删改查),parseStatementNode中addMappedStatement创建每个mapper对应的方法创建MappedStatement并添加到 configuration.mappedStatements.put(com.qb.mysql.dao.TRoleDao.getUserRoleByRid, MappedStatement)

最后返回了一个 DefaultSqlSessionFactory(config)

在调用SqlSessionTemplate进行dao层操作时,其会将工作委托给sqlSessionProxy属性进行,而sqlSessionProxy在进行相关method调用时,用到了JDK动态代理机制,首先SqlSessionUtils.getSqlSession获取sqlSession

 private class SqlSessionInterceptor implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//返回一个DefaultSqlsession
SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
//调用该类的MapperProxy的invoke方法
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
// release the connection to avoid a deadlock if the translator is no loaded. See issue #22
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
sqlSession = null;
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
if (sqlSession != null) {
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
}
}
在getSqlSession方法中创建事务,创建Executor,默认创建SimpleExecutor;InterceptorChain添加拦截器 InterceptorChain.pluginAll()

SqlSessionTemplate ->SqlSessionInterceptor->SqlSessionUtils. getSqlSession()->(defaultsqlsessionfactory)sessionFactory.openSession()->openSessionFromDataSource()

MapperProxy的invoke方法的方法
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
//执行execute
return mapperMethod.execute(sqlSession, args);
}
//根据sql类型选择对应的方法
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 {
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;
}

SqlSessionTemplate 执行了创建sqlsession,openSqlsession,执行sql,closeSqlsession

Mybatis的SqlSession理解(二)的更多相关文章

  1. Mybatis的SqlSession理解(一)

    SqlSession是Mybatis最重要的构建之一,可以认为Mybatis一系列的配置目的是生成类似JDBC生成的Connection对象的statement对象,这样才能与数据库开启“沟通”,通过 ...

  2. Mybatis源码解析(二) —— 加载 Configuration

    Mybatis源码解析(二) -- 加载 Configuration    正如上文所看到的 Configuration 对象保存了所有Mybatis的配置信息,也就是说mybatis-config. ...

  3. Java数据持久层框架 MyBatis之背景知识二

    对于MyBatis的学习而言,最好去MyBatis的官方文档:http://www.mybatis.org/mybatis-3/zh/index.html 对于语言的学习而言,马上上手去编程,多多练习 ...

  4. MyBatis基础入门《二》Select查询

    MyBatis基础入门<二>Select查询 使用MySQL数据库,创建表: SET NAMES utf8mb4; ; -- ---------------------------- -- ...

  5. mybatis 学习笔记(二):mybatis SQL注入问题

    mybatis 学习笔记(二):mybatis SQL注入问题 SQL 注入攻击 首先了解下概念,什么叫SQL 注入: SQL注入攻击,简称SQL攻击或注入攻击,是发生于应用程序之数据库层的安全漏洞. ...

  6. (转)MyBatis框架的学习(二)——MyBatis架构与入门

    http://blog.csdn.net/yerenyuan_pku/article/details/71699515 MyBatis框架的架构 MyBatis框架的架构如下图: 下面作简要概述: S ...

  7. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(2 配置spring-dao和测试)

    用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 搭建目录环境和依赖) 四:在\resources\spring 下面 ...

  8. 用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建二:配置MyBatis 并测试(1 构建目录环境和依赖)

    引言:在用IntelliJ IDEA 开发Spring+SpringMVC+Mybatis框架 分步搭建一   的基础上 继续进行项目搭建 该部分的主要目的是测通MyBatis 及Spring-dao ...

  9. Springboot & Mybatis 构建restful 服务二

    Springboot & Mybatis 构建restful 服务二 1 前置条件 成功执行完Springboot & Mybatis 构建restful 服务一 2 restful ...

随机推荐

  1. JS中常见原生DOM操作API

    摘自:https://blog.csdn.net/hj7jay/article/details/53389522 几种对象 Node Node是一个接口,中文叫节点,很多类型的DOM元素都是继承于它, ...

  2. php脚本#!/usr/bin/env php写法的好处

    脚本语言的第一行,目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它.比如php脚本的第一行可以写成如下几种格式#!/usr/bin/php#!/usr/bin/env php#!/us ...

  3. 微信小程序 windos server 2008 iis 7 tls1.0 升级 tls1.2

    执行下面注册表:重启服务器 下载:tls 1.2.reg 1.代码如下 Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\ ...

  4. opencv学习之路(17)、边缘检测

    一.概述 二.canny边缘检测 #include "opencv2/opencv.hpp" using namespace cv; void main() { //Canny边缘 ...

  5. django基础 -- 9.中间件

    一.中间件的介绍 中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级, 并且在全局上改变django的输入与输出.因为改变的是全局,所以需要谨慎实用, 用不好 ...

  6. topcoder srm 465 div1

    problem1 link 以两个点$p,q$为中心的两个正方形的边长和最大为$2dist(p,q)$,即$p,q$距离的两倍. 也就是两个$p,q$的连线垂直穿过两个正方形的一对边且平分两个正方形. ...

  7. topcoder srm 320 div1

    problem1 link 两个数字后面都有阶乘符号,可以抵消. import java.util.*; import java.math.*; import static java.lang.Mat ...

  8. SVM学习笔记5-SMO

    首先拿出最后要求解的问题:$\underset{\alpha}{min}W(\alpha)=\frac{1}{2} \sum_{i,j=1}^{n}y^{(i)}y^{(j)}\alpha_{i}\a ...

  9. Requests 源码阅读笔记

    models.py class Request(RequestHooksMixin): def __init__(self, method=None, url=None, headers=None, ...

  10. openwrt支持哪些c库?

    答: 至2019/3/22,支持两种,一种是glibc,另一种是musl-libc(openwrt默认使用musl-libc)