Mybatis主线流程源码解析

   Mybatis的基础使用以及与Spring的相关集成在官方文档都写的非常详细,但无论我们采用xml还是注解方式在使用的过程中经常会出现各种奇怪的问题,需要花费大量的时间解决。

抽空了解一下Mybatis的相关源码还是很有必要。

  先来看一个简单的Demo:

@Test
public void test() throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession session  = sqlSessionFactory.openSession();MethodInfo info = (MethodInfo) session.selectOne("com.ycdhz.mybatis.dao.MethodInfoMapper.selectById", 1);System.out.println(info.toString());
}

  这个是官网中入门的一段代码,我根据自己的情况做了一些参数上的改动。这段代码很容易理解,解析一个xml文件,通过SqlSessionFactoryBuilder构建一个SqlSessionFactory实例。

拿到了SqlSessionFactory我们就可以获取SqlSession。SqlSession 包含了面向数据库执行 SQL 命令所需的所有方法,所以我们可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。

代码很简单的展示了Mybatis到底是什么,有什么作用。

 

  Mybatis主线流程:解析Configuration返回SqlSessionFactory;拿到SqlSession对执行器进行初始化 SimpleExecutor;操作数据库;

  

 

  我们先来看一下mybatis-config.xml,在这个xml中包含了Mybatis的核心设置,有获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)等等。
具体的配置信息可以参考官方文档。需要注意的是Xml的属性配置有一定的顺序要求,具体的可以查看http://mybatis.org/dtd/mybatis-3-config.dtd。
<!ELEMENT configuration (properties?, settings?, typeAliases?, typeHandlers?, objectFactory?, objectWrapperFactory?, reflectorFactory?, plugins?, environments?, databaseIdProvider?, mappers?)>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mytest"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="mybatis/MethodInfoMapper.xml"/><!--<mapper class="com.ycdhz.mybatis.dao.MethodInfoMapper" />--><!--<package name="com.ycdhz.mybatis.dao" />--></mappers>
</configuration>

  test()前两行主要是通过流来读取配置文件,我们直接从new SqlSessionFactoryBuilder().build(inputStream)这段代码开始:

public class SqlSessionFactoryBuilder {public SqlSessionFactory build(InputStream inputStream) {return build(inputStream, null, null);}public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {try {// SqlSessionFactoryBuilde拿到输入流后,构建了一个XmlConfigBuilder的实例。通过parse()进行解析XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);return build(parser.parse());} catch (Exception e) {throw ExceptionFactory.wrapException("Error building SqlSession.", e);} finally {ErrorContext.instance().reset();try {inputStream.close();} catch (IOException e) {// Intentionally ignore. Prefer previous error.}}}public SqlSessionFactory build(Configuration config) {//XmlConfigBuilder.parse()解析完后将数据传给DefaultSqlSessionFactoryreturn new DefaultSqlSessionFactory(config);}
}

  

public class XMLConfigBuilder extends BaseBuilder {private boolean parsed;private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {super(new Configuration());ErrorContext.instance().resource("SQL Mapper Configuration");this.parsed = false;}public Configuration parse() {if (parsed) {throw new BuilderException("Each XMLConfigBuilder can only be used once.");}parsed = true;
     //这个方法主要就是解析xml文件了parseConfiguration(parser.evalNode("/configuration"));return configuration;}private void parseConfiguration(XNode root) {try {//issue #117 read properties firstpropertiesElement(root.evalNode("properties"));Properties settings = settingsAsProperties(root.evalNode("settings"));loadCustomVfs(settings);typeAliasesElement(root.evalNode("typeAliases"));pluginElement(root.evalNode("plugins"));objectFactoryElement(root.evalNode("objectFactory"));objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));reflectorFactoryElement(root.evalNode("reflectorFactory"));settingsElement(settings);// read it after objectFactory and objectWrapperFactory issue #631environmentsElement(root.evalNode("environments"));databaseIdProviderElement(root.evalNode("databaseIdProvider"));typeHandlerElement(root.evalNode("typeHandlers"));mapperElement(root.evalNode("mappers"));} catch (Exception e) {throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);}} }

   mybatis-config.xml 文件中的mapper属性支持四种配置方式,但是只有package,class这两种发式支持通过注解来配置和映射原生信息(原因在于configuration.addMappers()这个方法)。

private void mapperElement(XNode parent) throws Exception {if (parent != null) {for (XNode child : parent.getChildren()) {if ("package".equals(child.getName())) {String mapperPackage = child.getStringAttribute("name");configuration.addMappers(mapperPackage);} else {String resource = child.getStringAttribute("resource");String url = child.getStringAttribute("url");String mapperClass = child.getStringAttribute("class");if (resource != null && url == null && mapperClass == null) {ErrorContext.instance().resource(resource);InputStream inputStream = Resources.getResourceAsStream(resource);XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());mapperParser.parse();} else if (resource == null && url != null && mapperClass == null) {ErrorContext.instance().resource(url);InputStream inputStream = Resources.getUrlAsStream(url);XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());mapperParser.parse();} else if (resource == null && url == null && mapperClass != null) {Class<?> mapperInterface = Resources.classForName(mapperClass);configuration.addMapper(mapperInterface);} else {throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");}}}}}

   addMappers()调用了MapperAnnotationBuilder.parse()这样一段代码。我们发现当resource不为空的时候,代码首先会调用loadXmlResource()去Resource文件夹下查找(com/ycdhz/mybatis/dao/MethodInfoMapper.xml),

如果发现当前文件就加载。但实际这个时候type信息来自注解,MethodInfoMapper.xml在容器中被加载两次。所以Configruation下的静态类StrictMap.put()时会抛出一个 Mapped Statements collection already contains value for com.ycdhz.mybatis.dao.MethodInfoMapper.selectById 的异常

public class MapperAnnotationBuilder {public void parse() {String resource = type.toString();if (!configuration.isResourceLoaded(resource)) {loadXmlResource();configuration.addLoadedResource(resource);assistant.setCurrentNamespace(type.getName());parseCache();parseCacheRef();Method[] methods = type.getMethods();for (Method method : methods) {try {// issue #237if (!method.isBridge()) {parseStatement(method);}} catch (IncompleteElementException e) {configuration.addIncompleteMethod(new MethodResolver(this, method));}}}parsePendingMethods();}private void loadXmlResource() {// Spring may not know the real resource name so we check a flag// to prevent loading again a resource twice// this flag is set at XMLMapperBuilder#bindMapperForNamespaceif (!configuration.isResourceLoaded("namespace:" + type.getName())) {String xmlResource = type.getName().replace('.', '/') + ".xml";InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);} catch (IOException e) {// ignore, resource is not required}if (inputStream != null) {XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());xmlParser.parse();}}}
}

  

  这个时候我们已经完成了xml文件的解析过程,拿到了DefaultSqlSessionFactory。下面我们再来看一下sqlSessionFactory.openSession()的过程:

public class DefaultSqlSessionFactory implements SqlSessionFactory{private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {Transaction tx = null;try {final Environment environment = configuration.getEnvironment();final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);final Executor executor = configuration.newExecutor(tx, execType);return new DefaultSqlSession(configuration, executor, autoCommit);} catch (Exception e) {closeTransaction(tx); // may have fetched a connection so lets call close()throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);} finally {ErrorContext.instance().reset();}}
}public class Configuration {protected boolean cacheEnabled = true;protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;protected final InterceptorChain interceptorChain = new InterceptorChain();public Executor newExecutor(Transaction transaction, ExecutorType executorType) {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);}executor = (Executor) interceptorChain.pluginAll(executor);return executor;}
}

  

  openSession()方法会调用DefaultSqlSessionFactory.openSessionFromDataSource()方法,在这个方法中会开启事务、创建了执行器Executor:

  MyBatis的事务管理分为两种形式(配置mybatis-config.xml文件的transactionManager属性):

    1)使用JDBC的事务管理机制:即利用java.sql.Connection对象完成对事务的提交(commit())、回滚(rollback())、关闭(close())等

    2)使用MANAGED的事务管理机制:这种机制MyBatis自身不会去实现事务管理,而是让程序的容器如(JBOSS,Weblogic)来实现对事务的管理

     

   执行器ExecutorType分为三类(默认使用的是ExecutorType.SIMPLE):

    1)ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情。它为每个语句的执行创建一个新的预处理语句。

    2)ExecutorType.REUSE: 这个执行器类型会复用预处理语句。

    3)ExecutorType.BATCH: 这个执行器会批量执行所有更新语句,如果 SELECT 在它们中间执行还会标定它们是 必须的,来保证一个简单并易于理解的行为。 

        因为Mybatis的一级缓存是默认开启的,查看newExecutor()不难发现,最后通过CachingExecutor对SimpleExecutor进行了装饰(详细代码可以查看https://www.cnblogs.com/jiangyaxiong1990/p/9236764.html)

    

  Mybatis缓存设计成两级结构,分为一级缓存、二级缓存:(参考 https://blog.csdn.net/luanlouis/article/details/41280959 )

    1)一级缓存是Session会话级别的缓存,位于表示一次数据库会话的SqlSession对象之中,又被称之为本地缓存。默认情况下自动开启,用户没有定制它的权利(不过这也不是绝对的,可以通过开发插件对它进行修改);

      实际上MyBatis的一级缓存是使用PerpetualCache来维护的,PerpetualCache实现原理其实很简单,其内部就是通过一个简单的HashMap<k,v> 来实现的,没有其他的任何限制。

    2)二级缓存是Application应用级别的缓存,它的是生命周期很长,跟Application的声明周期一样,也就是说它的作用范围是整个Application应用。

          MyBatis的二级缓存设计得比较灵活,你可以使用MyBatis自己定义的二级缓存实现;你也可以通过实现org.apache.ibatis.cache.Cache接口自定义缓存;也可以使用第三方内存缓存库,如Redis等

  

 

 

    

 

 

  

转载于:https://www.cnblogs.com/jiangyaxiong1990/p/10306981.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/569876.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

动态规划之背包问题(C语言)

动态规划 动态规划&#xff08;英语&#xff1a;Dynamic programming&#xff0c;简称DP&#xff09;是一种通过把原问题分解为相对简单的子问题的方式求解复杂问题的方法。 动态规划常常适用于有重叠子问题和最优子结构性质的问题 动态规划思想大致上为&#xff1a;若要解一…

PHP函数-判断字符是否在于指定的字符串中

php中判断一个字符是否在字符串中 1、函数 以下四个函数都可以用来判断字符串中是否存在待查询的字符&#xff0c;可以是数字、字母或者符号。 strpos() - 查找字符串在另一字符串中第一次出现的位置&#xff08;区分大小写&#xff09; stripos() - 查找字符串在另一字符…

最大子列和问题(JAVA)

最大子列和 问题描述&#xff1a;给定N个整数的序列{A1&#xff0c;A2&#xff0c;A3&#xff0c;…&#xff0c;An}&#xff0c;求解子列和中最大的值。 这里我们给出{-2&#xff0c;11&#xff0c;-4&#xff0c;13&#xff0c;-5&#xff0c;-2}这样一个序列&#xff0c;正…

Oracle 11g必须开启的服务及服务详细介绍

成功安装Oracle 11g数据库后&#xff0c;你会发现自己电脑运行速度会变慢&#xff0c;配置较低的电脑甚至出现非常卡的状况&#xff0c;通过禁止非必须开启的Oracle服务可以提升电脑的运行速度。那么&#xff0c;具体该怎么做呢? 按照win7 64位环境下Oracle 11g R2安装详解中…

PHP—str_replace()替换函数的使用

一、str_replace()函数 1、定义和用法 str_replace() 函数替换字符串中的一些字符&#xff08;区分大小写&#xff09;。   注释&#xff1a;该函数是区分大小写的。请使用 str_ireplace() 函数执行不区分大小写的搜索。   注释&#xff1a;该函数是二进制安全的。 2、语…

JS/jQuery获取input的值和清空input的value值

一、获取input的值 1、通过普通选择器获取   通过类选择器获取&#xff1a;$(.class).val()   通过id选择器获取&#xff1a;$(" #id").val() 2、通过标签选择器获取   $(" input[ namename ] ").val()   $(" input[ typetext ] ").val…

JAVA刷题方法整理

JAVA刷题方法整理 一、String—>String[] 利用String.split()实现 注&#xff1a;在使用String.split 方法分隔字符串时&#xff0c;分隔符如果用到一些特殊字符&#xff0c;可能会得不到我们预期的结果&#xff0c;例如“|”&#xff0c;“*”&#xff0c;“”等&#x…

实现多线程Callable接口

Callable接口&#xff0c;实现多线程 1.实现 Callable接口&#xff0c;相较于实现 Runnable 接口的方式&#xff0c;优点是&#xff1a;方法可以有返回值&#xff0c;并且可以抛出异常 2.需要 FutureTask实现类的支持&#xff0c;用于接收运算结果 3.result.get()&#xff0c;接…

密码验证

用户在创建一个账户时&#xff0c;需要设置一个密码。密码的复杂程度是安全的保障之一&#xff0c;但是有些用户在设置密码时&#xff0c;总是把密码设置的过于简单&#xff0c;导致用户账户的安全存在威胁。因此&#xff0c;为了提高用户账户的安全性&#xff0c;添加了一个Ja…

阿里云windows/Linux 服务器建站教程,附WordPress配置方法

声明&#xff1a;文章仅供学习使用&#xff0c;故采用了多处链接&#xff0c;如有侵权&#xff0c;请私信我&#xff0c;立删。 最近看到一个学长做的验证界面&#xff0c;很简单的两个文本输入框&#xff0c;但是能给我们群里的小伙伴们做题提供一个验证答案的途径&#xff0…

Maven修改默认仓库为阿里云仓库

Maven 仓库默认在国外&#xff0c; 国内使用难免很慢&#xff0c;我们可以更换为阿里云的仓库。 第一步:修改 maven 根目录下的 conf 文件夹中的 setting.xml 文件&#xff0c;在 mirrors 节点上&#xff0c;添加内容如下&#xff1a; <mirrors><mirror><id>…

PHP语言结构详解

PHP语言结构 &#xff11;、语言结构释义   语言结构就是PHP语言的关键词&#xff0c;语言语法的一部分&#xff1b;   它不可以被用户定义或者添加到语言扩展或者库中&#xff1b;   它可以有也可以没有变量和返回值。 &#xff12;、为什么语言结构执行速度比函数快&…

查找算法——折半查找(JAVA)

折半查找 问题描述&#xff1a;给定一个整数X和整数A0&#xff0c;A1&#xff0c;A2……A(n-1)&#xff0c;后者已经预先排序并在内存中&#xff0c;求下标i使得Ai X &#xff0c;如果X不在数据中&#xff0c;则返回i -1。 我们首先可以想到的一种方法就是从左到右遍历&…

如何正确的检测对象类型?

在 javascript 中&#xff0c;我们常常用 typeof 运算符来检测对象的类型&#xff0c;在使用 typeof 检测引用类型的存储值会出现一个问题&#xff0c;无论引用的是什么类型的对象&#xff0c;它都会返回 "object"。这个时候我们往往会使用 instanceof instanceof 可…

PHP基于phpqrcode类生成二维码

使用ThinkPHP框架引入phpqrcode类生成二维码后&#xff0c;发现每次必须通过TP框架生成&#xff0c;略显繁琐&#xff0c;打算写一个简单的方法&#xff0c;然后运行php后直接批量生成二维码。方法也简单&#xff0c;直接写个PHP脚本&#xff0c;然后引入phpqrcode类&#xff0…

求最大公约数——欧几里得算法(JAVA)

欧几里得算法 问题描述&#xff1a;给出两个数m&#xff0c;n&#xff0c;求解这两个数的最大公因数 由于算法比较简单&#xff0c;这里不再赘述&#xff0c;我做的这个算法是默认了m>n,如果是对于任意两个数来说的话&#xff0c;我们这里还需要一个比较大小。 public cla…

编写函数digit(num, k),函数功能是:求整数num从右边开始的第k位数字的值,如果num位数不足k位则返回0。...

function digit(num,k){var knum 0;for(var i1; i<k; i){knum num%10;num parseInt(num/10);}return knum;}转载于:https://www.cnblogs.com/tis100204/p/10310140.html

JS/jQuery添加和移除CSS样式

有时候需要添加CSS样式和移除CSS样式&#xff0c;如添加display属性&#xff0c;设为隐藏。有时候需要移除display属性。 一、jQuery移除CSS样式的两种方法 注意&#xff1a;当其中一种不支持时&#xff0c;就尝试另一种&#xff1a; $("#show").removeAttr("…

高效幂运算(JAVA)--拆分解法、二进制解法

高效幂运算 问题描述&#xff1a;假设有一机器能够存储这样一些大整数&#xff08;或有一个编译程序能够模拟它&#xff09;&#xff0c;求一个相对大的数字&#xff08;一般为400位左右&#xff09;的极大幂&#xff08;400位左右&#xff09; 显然我们可以使用Java内置函数p…

动态规划之背包问题(JAVA)

背包问题之前的C语言版本已经将思路解析的差不多&#xff0c;虽然还有些许错误需要改正&#xff0c;但大体思路是正确的&#xff0c;需要的读者请参阅动态规划之背包问题&#xff08;C语言&#xff09; 背包问题本身就是典型的动态规划问题&#xff0c;所以这里只给出动态规划…