欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

持久层Mybatis3底层源码分析,原理解析

程序员文章站 2022-04-08 18:41:09
Mybatis-持久层的框架,功能是非常强大的,对于移动互联网的高并发 和 高性能是非常有利的,相对于Hibernate全自动的ORM框架,Mybatis简单,易于学习,sql编写在xml文件中,和代码分离,易于维护,属于半ORM框架,对于面向用户层面的互联网业务性能和并发,可以通过sql优化解决一 ......

mybatis-持久层的框架,功能是非常强大的,对于移动互联网的高并发 和 高性能是非常有利的,相对于hibernate全自动的orm框架,mybatis简单,易于学习,sql编写在xml文件中,和代码分离,易于维护,属于半orm框架,对于面向用户层面的互联网业务性能和并发,可以通过sql优化解决一些问题。

现如今大部分公司都在使用mybatis,所以我们要理解框架底层的原理。闲话不多说。

mybatis框架的核心入口 是sqlsessionfactory接口,我们先看一下它的代码

持久层Mybatis3底层源码分析,原理解析
public interface sqlsessionfactory {

  sqlsession opensession();

  sqlsession opensession(boolean autocommit);
  sqlsession opensession(connection connection);
  sqlsession opensession(transactionisolationlevel level);

  sqlsession opensession(executortype exectype);
  sqlsession opensession(executortype exectype, boolean autocommit);
  sqlsession opensession(executortype exectype, transactionisolationlevel level);
  sqlsession opensession(executortype exectype, connection connection);

  configuration getconfiguration();

}
sqlsessionfactory

sqlsessionfactory接口很多重载的opensession方法,返回sqlsession类型 对象, 还有configuration类(这个类非常强大,下面会梳理),我们先看一下sqlsession的代码

持久层Mybatis3底层源码分析,原理解析
public interface sqlsession extends closeable {

 
  <t> t selectone(string statement);


  <t> t selectone(string statement, object parameter);

  <e> list<e> selectlist(string statement);

  <e> list<e> selectlist(string statement, object parameter);

  <e> list<e> selectlist(string statement, object parameter, rowbounds rowbounds);

  <k, v> map<k, v> selectmap(string statement, string mapkey);
  <k, v> map<k, v> selectmap(string statement, object parameter, string mapkey);

  <k, v> map<k, v> selectmap(string statement, object parameter, string mapkey, rowbounds rowbounds);

  <t> cursor<t> selectcursor(string statement);
  <t> cursor<t> selectcursor(string statement, object parameter);

  <t> cursor<t> selectcursor(string statement, object parameter, rowbounds rowbounds);


  void select(string statement, object parameter, resulthandler handler);


  void select(string statement, resulthandler handler);


  list<batchresult> flushstatements();

  /**
   * closes the session
   */
  @override
  void close();

  void clearcache();


  configuration getconfiguration();


  <t> t getmapper(class<t> type);

  connection getconnection();
}
sqlseesion

只是展示了部分代码,但我们可以看到,sqlseesion里面 大多数方法是 增删改查的执行方法,包括查询返回不同的数据结构,比较注意的是clearcache()和getconnection()方法,一个是清楚缓存,一个是获取连接,获取数据库连接在这不在描述, 为什么要注意清楚缓存那,因为mybatis框架是实现了 缓存的,分为一级缓存,二级缓存,当增删改的时候就会调用此方法,删除缓存(后续会专门写一篇文章来分析mybatis缓存),先在这给大家熟悉一下。

上面的sqlsessionfactory和sqlseesion都是接口,我们在看一下实现类defaultsqlsessionfactory和defaultsqlsession,下面展示defaultsqlsessionfactory的比较核心的代码

持久层Mybatis3底层源码分析,原理解析
 1   private sqlsession opensessionfromdatasource(executortype exectype, transactionisolationlevel level, boolean autocommit) {
 2     transaction tx = null;
 3     try {
 4       final environment environment = configuration.getenvironment();
 5       final transactionfactory transactionfactory = gettransactionfactoryfromenvironment(environment);
 6       tx = transactionfactory.newtransaction(environment.getdatasource(), level, autocommit);
 7       final executor executor = configuration.newexecutor(tx, exectype);
 8       return new defaultsqlsession(configuration, executor, autocommit);
 9     } catch (exception e) {
10       closetransaction(tx); // may have fetched a connection so lets call close()
11       throw exceptionfactory.wrapexception("error opening session.  cause: " + e, e);
12     } finally {
13       errorcontext.instance().reset();
14     }
15   }
defaultsqlsessionfactory

其实sqlsessionfactory中的多个重载openseesion方法最终都是执行的这个方法,我们可以看到这个方法中 通过 configuration属性 获取到executor 执行器对象,defaultsqlsession构造器把这configuration和executor当成构造参数,初始化创建一个 defaultsqlsession对象,然后我们在展示一下defaultsqlsession代码中的大家一看就理解的代码

持久层Mybatis3底层源码分析,原理解析
 1   public <e> list<e> selectlist(string statement, object parameter, rowbounds rowbounds) {
 2     try {
 3       mappedstatement ms = configuration.getmappedstatement(statement);
 4       return executor.query(ms, wrapcollection(parameter), rowbounds, executor.no_result_handler);
 5     } catch (exception e) {
 6       throw exceptionfactory.wrapexception("error querying database.  cause: " + e, e);
 7     } finally {
 8       errorcontext.instance().reset();
 9     }
10   }
defaultsession

看到这个方法大家估计就会看明白了,底层执行的就是 通过executor 对象执行的 查询, 通过configuration获取到 要执行的sql,获取到我们需要的结果。

从上面代码可以看出 configuration 类无处不在,那我们就去看一下源码

持久层Mybatis3底层源码分析,原理解析
 1 public class configuration {
 2 
 3   protected environment environment;
 4 
 5   protected boolean saferowboundsenabled;
 6   protected boolean saferesulthandlerenabled = true;
 7   protected boolean mapunderscoretocamelcase;
 8   protected boolean aggressivelazyloading;
 9   protected boolean multipleresultsetsenabled = true;
10   protected boolean usegeneratedkeys;
11   protected boolean usecolumnlabel = true;
12   protected boolean cacheenabled = true;
13   protected boolean callsettersonnulls;
14   protected boolean useactualparamname = true;
15   protected boolean returninstanceforemptyrow;
16 
17   protected string logprefix;
18   protected class <? extends log> logimpl;
19   protected class <? extends vfs> vfsimpl;
20   protected localcachescope localcachescope = localcachescope.session;
21   protected jdbctype jdbctypefornull = jdbctype.other;
22   protected set<string> lazyloadtriggermethods = new hashset<string>(arrays.aslist(new string[] { "equals", "clone", "hashcode", "tostring" }));
23   protected integer defaultstatementtimeout;
24   protected integer defaultfetchsize;
25   protected executortype defaultexecutortype = executortype.simple;
26   protected automappingbehavior automappingbehavior = automappingbehavior.partial;
27   protected automappingunknowncolumnbehavior automappingunknowncolumnbehavior = automappingunknowncolumnbehavior.none;
28 
29   protected properties variables = new properties();
30   protected reflectorfactory reflectorfactory = new defaultreflectorfactory();
31   protected objectfactory objectfactory = new defaultobjectfactory();
32   protected objectwrapperfactory objectwrapperfactory = new defaultobjectwrapperfactory();
33 
34   protected boolean lazyloadingenabled = false;
35   protected proxyfactory proxyfactory = new javassistproxyfactory(); // #224 using internal javassist instead of ognl
36 
37   protected string databaseid;
38   /**
39    * configuration factory class.
40    * used to create configuration for loading deserialized unread properties.
41    *
42    * @see <a href='https://code.google.com/p/mybatis/issues/detail?id=300'>issue 300 (google code)</a>
43    */
44   protected class<?> configurationfactory;
45 
46   protected final mapperregistry mapperregistry = new mapperregistry(this);
47   protected final interceptorchain interceptorchain = new interceptorchain();
48   protected final typehandlerregistry typehandlerregistry = new typehandlerregistry();
49   protected final typealiasregistry typealiasregistry = new typealiasregistry();
50   protected final languagedriverregistry languageregistry = new languagedriverregistry();
51 
52   protected final map<string, mappedstatement> mappedstatements = new strictmap<mappedstatement>("mapped statements collection");
53   protected final map<string, cache> caches = new strictmap<cache>("caches collection");
54   protected final map<string, resultmap> resultmaps = new strictmap<resultmap>("result maps collection");
55   protected final map<string, parametermap> parametermaps = new strictmap<parametermap>("parameter maps collection");
56   protected final map<string, keygenerator> keygenerators = new strictmap<keygenerator>("key generators collection");
57 
58   protected final set<string> loadedresources = new hashset<string>();
59   protected final map<string, xnode> sqlfragments = new strictmap<xnode>("xml fragments parsed from previous mappers");
60 
61   protected final collection<xmlstatementbuilder> incompletestatements = new linkedlist<xmlstatementbuilder>();
62   protected final collection<cacherefresolver> incompletecacherefs = new linkedlist<cacherefresolver>();
63   protected final collection<resultmapresolver> incompleteresultmaps = new linkedlist<resultmapresolver>();
64   protected final collection<methodresolver> incompletemethods = new linkedlist<methodresolver>();
65 
66   /*
67    * a map holds cache-ref relationship. the key is the namespace that
68    * references a cache bound to another namespace and the value is the
69    * namespace which the actual cache is bound to.
70    */
71   protected final map<string, string> cacherefmap = new hashmap<string, string>();}
configuration

上面的代码都是 configuration类中的属性值,上面的boolean 类型的属性 都是一些配置的属性,比如usegeneratedkeys是否开启使用返回主键,cacheenabled是否开启缓存等等,下面的map类型的 就是存储一些我们项目中需要编写的sql.xml文件,我们可以通过变量名大致推测出来存储的结果,比如typealiasregistry 存储的别名,mappedstatements 存储的sql,resultmaps存储的结果等,当然这些map的key对应的就是 sql.xml中的唯一的id,分析到现在,我们大致知道mybatis框架底层的执行原理了。

但是,这时候就有个疑问了,入口类是sqlsessionfactory,那是怎么加载资源的那,我们通过名称寻找源码,可以找到一个sqlsessionfactorybuilder(这些开发开源框架的牛人们不管技术nb,对类的命名也是很值的大家效仿的),builder--加载, 说明这个类就是加载 sqlsessionfactory,我们看一下代码

持久层Mybatis3底层源码分析,原理解析
 1 public class sqlsessionfactorybuilder {
 2 
 3   public sqlsessionfactory build(reader reader) {
 4     return build(reader, null, null);
 5   }
 6 
 7   public sqlsessionfactory build(reader reader, string environment) {
 8     return build(reader, environment, null);
 9   }
10 
11   public sqlsessionfactory build(reader reader, properties properties) {
12     return build(reader, null, properties);
13   }
14 
15   public sqlsessionfactory build(reader reader, string environment, properties properties) {
16     try {
17       xmlconfigbuilder parser = new xmlconfigbuilder(reader, environment, properties);
18       return build(parser.parse());
19     } catch (exception e) {
20       throw exceptionfactory.wrapexception("error building sqlsession.", e);
21     } finally {
22       errorcontext.instance().reset();
23       try {
24         reader.close();
25       } catch (ioexception e) {
26         // intentionally ignore. prefer previous error.
27       }
28     }
29   }
30 
31   public sqlsessionfactory build(inputstream inputstream) {
32     return build(inputstream, null, null);
33   }
34 
35   public sqlsessionfactory build(inputstream inputstream, string environment) {
36     return build(inputstream, environment, null);
37   }
38 
39   public sqlsessionfactory build(inputstream inputstream, properties properties) {
40     return build(inputstream, null, properties);
41   }
42 
43   public sqlsessionfactory build(inputstream inputstream, string environment, properties properties) {
44     try {
45       xmlconfigbuilder parser = new xmlconfigbuilder(inputstream, environment, properties);
46       return build(parser.parse());
47     } catch (exception e) {
48       throw exceptionfactory.wrapexception("error building sqlsession.", e);
49     } finally {
50       errorcontext.instance().reset();
51       try {
52         inputstream.close();
53       } catch (ioexception e) {
54         // intentionally ignore. prefer previous error.
55       }
56     }
57   }
58     
59   public sqlsessionfactory build(configuration config) {
60     return new defaultsqlsessionfactory(config);
61   }
62 
63 }
sqlsessionfactorybuilder

查看代码中的build方法,可以看出是 通过流来加载xml文件 ,包括mybatis的配置文件和 sql.xml文件,返回一个defaultsqlsessionfactory 对象。

本篇文件只是介绍了mybatis的底层执行原理,喜欢深入了解的可以自己去深入了解一下。

以上是个人理解,欢迎大家来讨论,不喜勿喷!谢谢!!

如转载,请注明转载地址,谢谢