Mybatis分层架构
Mybatis主要分为三层,接口层负责提供数据的增删改查接口、数据处理层则负责具体SQL的执行、框架层则提供Mybatis的底层配置,如数据源、具体sql、事务等配置
Mybatis的请求处理过程
Mysql执行请求主要是通过SqlSession来进行的,SqlSession作为最顶层的接口,提供增删改查,内部交给Executor去执行(其有几个不同的实现类,分别用来处理不同的查询以及一级和二级缓存)
Mybatis的缓存设计
Mybatis支持一级缓存和二级缓存。
一级缓存默认是会话级别的,也可以通过在Configuration中配置,来设置为statement级别。
<setting name="localCacheScope" value="SESSION"/>
二级缓存则可以跨会话,是NameSpace级别的,二级缓存需要在Configuration开启Cache,并在需要缓存的NameSpace下配置Cache标签
//config.xml中开启二级缓存<setting name="cacheEnabled" value="true"/>//xxxMapper.xml中配置cache,默认是本地缓存,可以指定为其他外部缓存<cache/>
Mybatis源码知识脑图
SqlSessionFactory
SqlSessionFactory是Mybatis的SqlSession会话工厂,用来获得一个会话。前面我们已经看到所有的请求都是通过SqlSession进行处理的。当Mybatis与Spring整合时,其作为一个Bean是通过SqlSessionFactoryBean来实例化的,其内部主要通过SqlSessionFactoryBuilder来进行构造,build方法需要一个Configuration实例。其默认实现是DefaultSqlSessionFactory
//SqlSessionFactoryBeanprotected SqlSessionFactory buildSqlSessionFactory() throws IOException {Configuration configuration;//这里解析config.xml、xxxMapper.xml等配置文件得到Configuration实例XMLConfigBuilder xmlConfigBuilder = null;if (this.configLocation != null) {xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);configuration = xmlConfigBuilder.getConfiguration();} else {if (logger.isDebugEnabled()) {logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration");}configuration = new Configuration();configuration.setVariables(this.configurationProperties);}if (this.objectFactory != null) {configuration.setObjectFactory(this.objectFactory);}if (this.objectWrapperFactory != null) {configuration.setObjectWrapperFactory(this.objectWrapperFactory);}if (hasLength(this.typeAliasesPackage)) {String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);for (String packageToScan : typeAliasPackageArray) {configuration.getTypeAliasRegistry().registerAliases(packageToScan,typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);if (logger.isDebugEnabled()) {logger.debug("Scanned package: '" + packageToScan + "' for aliases");}}}if (!isEmpty(this.typeAliases)) {for (Class<?> typeAlias : this.typeAliases) {configuration.getTypeAliasRegistry().registerAlias(typeAlias);if (logger.isDebugEnabled()) {logger.debug("Registered type alias: '" + typeAlias + "'");}}}if (!isEmpty(this.plugins)) {for (Interceptor plugin : this.plugins) {configuration.addInterceptor(plugin);if (logger.isDebugEnabled()) {logger.debug("Registered plugin: '" + plugin + "'");}}}if (hasLength(this.typeHandlersPackage)) {String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage,ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);for (String packageToScan : typeHandlersPackageArray) {configuration.getTypeHandlerRegistry().register(packageToScan);if (logger.isDebugEnabled()) {logger.debug("Scanned package: '" + packageToScan + "' for type handlers");}}}if (!isEmpty(this.typeHandlers)) {for (TypeHandler<?> typeHandler : this.typeHandlers) {configuration.getTypeHandlerRegistry().register(typeHandler);if (logger.isDebugEnabled()) {logger.debug("Registered type handler: '" + typeHandler + "'");}}}if (xmlConfigBuilder != null) {try {xmlConfigBuilder.parse();if (logger.isDebugEnabled()) {logger.debug("Parsed configuration file: '" + this.configLocation + "'");}} catch (Exception ex) {throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex);} finally {ErrorContext.instance().reset();}}if (this.transactionFactory == null) {this.transactionFactory = new SpringManagedTransactionFactory();}Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource);configuration.setEnvironment(environment);if (this.databaseIdProvider != null) {try {configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource));} catch (SQLException e) {throw new NestedIOException("Failed getting a databaseId", e);}}//解析Bean中配置mapperLocation中指定的xml文件,与Spring集成后一般不会直接写在config.xml中if (!isEmpty(this.mapperLocations)) {for (Resource mapperLocation : this.mapperLocations) {if (mapperLocation == null) {continue;}try {XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(),configuration, mapperLocation.toString(), configuration.getSqlFragments());xmlMapperBuilder.parse();} catch (Exception e) {throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e);} finally {ErrorContext.instance().reset();}if (logger.isDebugEnabled()) {logger.debug("Parsed mapper file: '" + mapperLocation + "'");}}} else {if (logger.isDebugEnabled()) {logger.debug("Property 'mapperLocations' was not specified or no matching resources found");}}return this.sqlSessionFactoryBuilder.build(configuration);}
Configuration
Configuration也是Mybatis一个非常核心的类,实例这个对象需要解析Mybatis的config.xml文件和所有的Mapper.xml文件,并为每个Statement建立一个缓存,还会为每个Mapper接口绑定一个MapperProxyFactory工厂。Configuration解析配置文件主要通过XmlConfigBuilder、XmlMapperBuilder、XmlStatementBuild来分别解析全局配置文件、Mapper配置文件和具体的Statement配置
SqlSession
SqlSession里面定义了增删改查的方法,其默认实现为DefaultSqlSession,通过SqlSessionFactory进行获取,下面主要看两个问题:
(1)Mapper接口的查询是如何被代理的
通常我们只需要定义查询的Dao接口,但不需要实现,而Mybatis是通过动态代理来实现的,具体可以查看DefaultSqlSession的getMapper方法
//DefaultSqlSessionpublic <T> T getMapper(Class<T> type) {return configuration.<T>getMapper(type, this);}//Configurationpublic <T> T getMapper(Class<T> type, SqlSession sqlSession) {return mapperRegistry.getMapper(type, sqlSession);}//MapperRegistrypublic <T> T getMapper(Class<T> type, SqlSession sqlSession) {final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);if (mapperProxyFactory == null)throw new BindingException("Type " + type + " is not known to the MapperRegistry.");try {return mapperProxyFactory.newInstance(sqlSession);} catch (Exception e) {throw new BindingException("Error getting mapper instance. Cause: " + e, e);}}//MapperProxyFactory//这里使用了jdk的动态代理,为Mapper生成了一个代理类protected T newInstance(MapperProxy<T> mapperProxy) {return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);}public T newInstance(SqlSession sqlSession) {final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);return newInstance(mapperProxy);}//MapperProxy//MapperProxy实现了InvocationHandler接口,来进行代理,一般的invoke方法都会调用被代理接口的实现类的具体方法,//但是Mybatis里实际上只有Mapper接口,这里并没有实现类,而是直接将请求交给了MapperMethod去处理了public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {if (Object.class.equals(method.getDeclaringClass())) {try {return method.invoke(this, args);} catch (Throwable t) {throw ExceptionUtil.unwrapThrowable(t);}}final MapperMethod mapperMethod = cachedMapperMethod(method);return mapperMethod.execute(sqlSession, args);}private MapperMethod cachedMapperMethod(Method method) {MapperMethod mapperMethod = methodCache.get(method);if (mapperMethod == null) {mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());methodCache.put(method, mapperMethod);}return mapperMethod;}//MapperMethod, 可以看出最终内部是通过SqlSession对应的curd接口进行数据库的操作的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;}
(2)SqlSession是如何执行Sql的
这里以selectOne为例,其内部会调用selectList,然后会交给Executor去执行,而具体使用哪个Executor是依据Sql类型来决定的,如果开启了二级缓存,还会用CachingExecutor对内部实际的Executor进行包装
//DefaultSqlSessionpublic <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {try {//从Configuration中拿到对应的StatementMappedStatement ms = configuration.getMappedStatement(statement);//调用executor的queryList<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);return result;} catch (Exception e) {throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);} finally {ErrorContext.instance().reset();}}//BaseExecutorpublic <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {BoundSql boundSql = ms.getBoundSql(parameter);CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);return query(ms, parameter, rowBounds, resultHandler, key, boundSql);}public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());if (closed) throw new ExecutorException("Executor was closed.");if (queryStack == 0 && ms.isFlushCacheRequired()) {clearLocalCache();}List<E> list;try {queryStack++;//这里有一个localCache,实际上就是一级缓存,内部是一个HashMaplist = resultHandler == null ? (List<E>) localCache.getObject(key) : null;if (list != null) {handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);} else {list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);}} finally {queryStack--;}if (queryStack == 0) {for (DeferredLoad deferredLoad : deferredLoads) {deferredLoad.load();}deferredLoads.clear(); // issue #601if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {clearLocalCache(); // issue #482}}return list;}//查数据库private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {List<E> list;localCache.putObject(key, EXECUTION_PLACEHOLDER);try {//这里使用了模板方法设计模式,doQuery的逻辑交给BaseExecutor的子类去实现list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);} finally {localCache.removeObject(key);}localCache.putObject(key, list);if (ms.getStatementType() == StatementType.CALLABLE) {localOutputParameterCache.putObject(key, parameter);}return list;}//SimpleExecutor的实现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(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);stmt = prepareStatement(handler, ms.getStatementLog());//调用StatementHandler的query方法去查询, 底层是基于jdbc的PreparedStatement、statement等来查询数据return handler.<E>query(stmt, resultHandler);} finally {closeStatement(stmt);}}//这里以PreparedStatementHandler的实现,得到数据之后通过ResultSetHandler来处理返回值public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {PreparedStatement ps = (PreparedStatement) statement;ps.execute();return resultSetHandler.<E> handleResultSets(ps);}
Executor的实现类如下:
StatementHandler的实现类:
Cache的实现类:里面的很多类都采用了装饰器模式,来装饰底层的cache
装饰链路:SynchronizedCache -> LoggingCache -> SerializedCache -> LruCache -> PerpetualCache。

其中LRUCache的实现是基于LinkedHashMap来实现的, 主要是重写其removeEldestEntry方法。如果是自己实现,可以基于HashMap + LinkedList来实现
public class LruCache implements Cache {private final Cache delegate;private Map<Object, Object> keyMap;private Object eldestKey;public LruCache(Cache delegate) {this.delegate = delegate;setSize(1024);}@Overridepublic String getId() {return delegate.getId();}@Overridepublic int getSize() {return delegate.getSize();}public void setSize(final int size) {keyMap = new LinkedHashMap<Object, Object>(size, .75F, true) {private static final long serialVersionUID = 4267176411845948333L;protected boolean removeEldestEntry(Map.Entry<Object, Object> eldest) {boolean tooBig = size() > size;if (tooBig) {eldestKey = eldest.getKey();}return tooBig;}};}@Overridepublic void putObject(Object key, Object value) {delegate.putObject(key, value);cycleKeyList(key);}@Overridepublic Object getObject(Object key) {keyMap.get(key); //touchreturn delegate.getObject(key);}@Overridepublic Object removeObject(Object key) {return delegate.removeObject(key);}@Overridepublic void clear() {delegate.clear();keyMap.clear();}public ReadWriteLock getReadWriteLock() {return null;}private void cycleKeyList(Object key) {keyMap.put(key, key);if (eldestKey != null) {delegate.removeObject(eldestKey);eldestKey = null;}}
写在最后
Mybatis虽然解决Java对象和数据库之间的ORM映射,为开发省去了手写jdbc和事务等重复的逻辑。但目前的数据库架构早已告别了单机时代,而集群时代又将面临很多Mybatis所解决不了的问题,如更多的数据、更高的并发等,因而就衍生了支持读写分离和分库分表的更上层的数据访问层的中间件
