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


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

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

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

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的代码

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的比较核心的代码

 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代码中的大家一看就理解的代码

 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 类无处不在,那我们就去看一下源码

 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,我们看一下代码

 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的底层执行原理,喜欢深入了解的可以自己去深入了解一下。

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

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM