public <T> T getMapper(Class<T> type) { return configuration.getMapper(type, this); } public <T> T getMapper(Class<T> type, SqlSession sqlSession) { //从mapperRegister找,在解析Mapper配置文件时,根据nameSpace 注册mapper接口道mapperRegister return mapperRegistry.getMapper(type, sqlSession); } public <T> T getMapper(Class<T> type, SqlSession sqlSession) { if (!knownMappers.contains(type)) throw new BindingException("Type " + type + " is not known to the MapperRegistry."); try { //返回mapper接口类代理 return MapperProxy.newMapperProxy(type, sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
所有调接口的方法都会被代理类拦截处理我们看具体实现
@SuppressWarnings("unchecked") public static <T> T newMapperProxy(Class<T> mapperInterface, SqlSession sqlSession) { ClassLoader classLoader = mapperInterface.getClassLoader(); Class<?>[] interfaces = new Class[]{mapperInterface}; //这个是处理的handle MapperProxy proxy = new MapperProxy(sqlSession); return (T) Proxy.newProxyInstance(classLoader, interfaces, proxy); } } //MapperProxy 回调的入口 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!OBJECT_METHODS.contains(method.getName())) { //找到方法所属的接口 final Class<?> declaringInterface = findDeclaringInterface(proxy, method); final MapperMethod mapperMethod = new MapperMethod(declaringInterface, method, sqlSession); final Object result = mapperMethod.execute(args); if (result == null && method.getReturnType().isPrimitive() && !method.getReturnType().equals(Void.TYPE)) { throw new BindingException("Mapper method '" + method.getName() + "' (" + method.getDeclaringClass() + ") attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; } return null; } public Object execute(Object[] args) { Object result = null; if (SqlCommandType.INSERT == type) { Object param = getParam(args); result = sqlSession.insert(commandName, param); } else if (SqlCommandType.UPDATE == type) { Object param = getParam(args); result = sqlSession.update(commandName, param); } else if (SqlCommandType.DELETE == type) { Object param = getParam(args); result = sqlSession.delete(commandName, param); } else if (SqlCommandType.SELECT == type) { if (returnsVoid && resultHandlerIndex != null) { executeWithResultHandler(args); } else if (returnsList) { result = executeForList(args); } else if (returnsMap) { result = executeForMap(args); } else { Object param = getParam(args); result = sqlSession.selectOne(commandName, param); } } else { throw new BindingException("Unknown execution method for: " + commandName); } return result; }
上面这些方法最终都会由sqlSession调用Executer来执行
来看个查询返回List例子
private List executeForList(Object[] args) { List result; Object param = getParam(args); if (rowBoundsIndex != null) { RowBounds rowBounds = (RowBounds) args[rowBoundsIndex]; result = sqlSession.selectList(commandName, param, rowBounds); } else { result = sqlSession.selectList(commandName, param); } return result; } public List selectList(String statement, Object parameter, RowBounds rowBounds) { try { MappedStatement ms = configuration.getMappedStatement(statement); return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } } public List query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { if (ms != null) { Cache cache = ms.getCache(); if (cache != null) { flushCacheIfRequired(ms); cache.getReadWriteLock().readLock().lock(); try { if (ms.isUseCache() && resultHandler == null) { CacheKey key = createCacheKey(ms, parameterObject, rowBounds); final List cachedList = (List) cache.getObject(key); if (cachedList != null) { return cachedList; } else { List list = delegate.query(ms, parameterObject, rowBounds, resultHandler); tcm.putObject(cache, key, list); return list; } } else { return delegate.query(ms, parameterObject, rowBounds, resultHandler); } } finally { cache.getReadWriteLock().readLock().unlock(); } } } return delegate.query(ms, parameterObject, rowBounds, resultHandler); }
从上面我们可以看到先回从缓存找找不到在从delegate类找,delete就是普通的Executor,
普通Executor有3类,他们都继承于BaseExecutor,BatchExecutor专门用于执行批量sql操作,ReuseExecutor会重用statement执行sql操作,SimpleExecutor只是简单执行sql没有什么特别的。下面以SimpleExecutor为例:
public List doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { Statement stmt = null; try { Configuration configuration = ms.getConfiguration(); StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, rowBounds, resultHandler); stmt = prepareStatement(handler); return handler.query(stmt, resultHandler); } finally { closeStatement(stmt); } }
StatementHandler
当Executor将指挥棒交给StatementHandler后,接下来的工作就是StatementHandler的事了。我们先看看StatementHandler是如何创建的。
创建
publicStatementHandler newStatementHandler(Executor executor, MappedStatementmappedStatement,
ObjectparameterObject, RowBounds rowBounds, ResultHandler resultHandler) {
StatementHandler statementHandler = newRoutingStatementHandler(executor, mappedStatement,parameterObject,rowBounds, resultHandler);
statementHandler= (StatementHandler) interceptorChain.pluginAll(statementHandler);
returnstatementHandler;
}
可以看到每次创建的StatementHandler都是RoutingStatementHandler,它只是一个分发者,他一个属性delegate用于指定用哪种具体的StatementHandler。可选的StatementHandler有SimpleStatementHandler、PreparedStatementHandler和CallableStatementHandler三种。选用哪种在mapper配置文件的每个statement里指定,默认的是PreparedStatementHandler。同时还要注意到StatementHandler是可以被拦截器拦截的,和Executor一样,被拦截器拦截后的对像是一个代理对象。由于mybatis没有实现数据库的物理分页,众多物理分页的实现都是在这个地方使用拦截器实现的,本文作者也实现了一个分页拦截器,在后续的章节会分享给大家,敬请期待。
初始化
StatementHandler创建后需要执行一些初始操作,比如statement的开启和参数设置、对于PreparedStatement还需要执行参数的设置操作等。代码如下:
private StatementprepareStatement(StatementHandler handler) throwsSQLException {
Statementstmt;
Connectionconnection = transaction.getConnection();
stmt =handler.prepare(connection);
handler.parameterize(stmt);
return stmt;
}
statement的开启和参数设置没什么特别的地方,handler.parameterize倒是可以看看是怎么回事。handler.parameterize通过调用ParameterHandler的setParameters完成参数的设置,ParameterHandler随着StatementHandler的创建而创建,默认的实现是DefaultParameterHandler:
publicParameterHandler newParameterHandler(MappedStatement mappedStatement, ObjectparameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement,parameterObject,boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
returnparameterHandler;
}
同Executor和StatementHandler一样,ParameterHandler也是可以被拦截的。
参数设置
DefaultParameterHandler里设置参数的代码如下:
[java] view plaincopy
publicvoidsetParameters(PreparedStatement ps) throwsSQLException {
ErrorContext.instance().activity("settingparameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if(parameterMappings != null) {
MetaObject metaObject = parameterObject == null ? null :configuration.newMetaObject(parameterObject);
for (int i = 0; i< parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if(parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
PropertyTokenizer prop = newPropertyTokenizer(propertyName);
if (parameterObject == null) {
value = null;
} elseif (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())){
value = parameterObject;
} elseif (boundSql.hasAdditionalParameter(propertyName)){
value = boundSql.getAdditionalParameter(propertyName);
} elseif(propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)
&& boundSql.hasAdditionalParameter(prop.getName())){
value = boundSql.getAdditionalParameter(prop.getName());
if (value != null) {
value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
}
} else {
value = metaObject == null ? null :metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
thrownew ExecutorException("Therewas no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
}
typeHandler.setParameter(ps, i + 1, value,parameterMapping.getJdbcType());
}
}
}
}
这里面最重要的一句其实就是最后一句代码,它的作用是用合适的TypeHandler完成参数的设置。那么什么是合适的TypeHandler呢,它又是如何决断出来的呢?BaseStatementHandler的构造方法里有这么一句:
this.boundSql= mappedStatement.getBoundSql(parameterObject);
它触发了sql 的解析,在解析sql的过程中,TypeHandler也被决断出来了,决断的原则就是根据参数的类型和参数对应的JDBC类型决定使用哪个TypeHandler。比如:参数类型是String的话就用StringTypeHandler,参数类型是整数的话就用IntegerTypeHandler等。
参数设置完毕后,执行数据库操作(update或query)。如果是query最后还有个查询结果的处理过程。
结果处理
结果处理使用ResultSetHandler来完成,默认的ResultSetHandler是FastResultSetHandler,它在创建StatementHandler时一起创建,代码如下:
publicResultSetHandler newResultSetHandler(Executor executor, MappedStatementmappedStatement,
RowBoundsrowBounds, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSqlboundSql) {
ResultSetHandler resultSetHandler =mappedStatement.hasNestedResultMaps() ? newNestedResultSetHandler(executor, mappedStatement, parameterHandler,resultHandler, boundSql, rowBounds): new FastResultSetHandler(executor,mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
returnresultSetHandler;
}
可以看出ResultSetHandler也是可以被拦截的,可以编写自己的拦截器改变ResultSetHandler的默认行为。
- ResultSetHandler内部一条记录一条记录的处理,在处理每条记录的每一列时会调用TypeHandler转换结果,如下:
-
protectedbooleanapplyAutomaticMappings(ResultSet rs, List<String> unmappedColumnNames,MetaObject metaObject) throws SQLException { booleanfoundValues = false; for (StringcolumnName : unmappedColumnNames) { final Stringproperty = metaObject.findProperty(columnName); if (property!= null) { final ClasspropertyType =metaObject.getSetterType(property); if (typeHandlerRegistry.hasTypeHandler(propertyType)) { final TypeHandler typeHandler = typeHandlerRegistry.getTypeHandler(propertyType); final Object value = typeHandler.getResult(rs,columnName); if (value != null) { metaObject.setValue(property, value); foundValues = true; } } } } returnfoundValues; }
从代码里可以看到,决断TypeHandler使用的是结果参数的属性类型。因此我们在定义作为结果的对象的属性时一定要考虑与数据库字段类型的兼容性。
相关推荐
本资源“mybatis源码分析视频”是针对MyBatis框架进行深入剖析的教程,通过视频和文档的形式帮助学习者理解其内部工作机制。 1. **MyBatis简介** MyBatis消除了几乎所有的JDBC代码和手动设置参数以及获取结果集。...
总结起来,MyBatis源码分析涵盖了从配置加载到数据库操作的全过程,涉及到了配置解析、SQL执行、结果映射等多个关键环节,以及Executor、StatementHandler等核心组件。通过深入学习MyBatis的源码,开发者不仅可以...
MyBatis是一款流行的Java...总的来说,MyBatis源码分析思维导图会涵盖MyBatis的各个关键组件、工作流程、特性以及扩展机制。通过深入学习和理解这些内容,开发者能够更好地利用MyBatis进行数据库操作,并优化其性能。
要整合MyBatis与通用Mapper,我们需要在项目中引入相应的依赖,配置MapperScannerConfigurer扫描Mapper接口,然后在Dao接口上添加通用Mapper的注解,如`@Select`、`@Insert`等。 在实际操作中,我们还需要创建一个...
通过对MyBatis源码的分析,开发者可以更深入地理解其内部运作机制,从而更好地优化应用,解决实际问题。同时,这也是一种提升个人技术水平和解决问题能力的有效途径。在阅读源码过程中,可能会遇到各种设计模式和...
《MyBatis源码分析与实战应用》 在IT行业中,MyBatis作为一个轻量级的持久层框架,因其灵活性和高效性而被广泛应用。它将SQL语句与Java代码相结合,提供了比传统JDBC更方便的数据操作方式。本文将深入探讨MyBatis的...
《MyBatis源码详解学习》是一份专为对MyBatis源码感兴趣的开发者准备的资料,它旨在帮助读者深入理解这个流行持久层框架的工作原理。MyBatis作为一个轻量级的ORM(对象关系映射)框架,因其简单易用、高度可定制化的...
《一本小小的MyBatis源码分析书》是针对Java开发者,特别是初中级开发工程师的一份重要参考资料,专注于解析MyBatis这一流行持久层框架的源代码。MyBatis作为一个轻量级的ORM(对象关系映射)框架,它极大地简化了...
在深入学习Mybatis源码的过程中,我们可以了解到它的工作原理,更好地优化数据库交互,提高程序性能。 1. **Mybatis概述** Mybatis 源码的学习可以帮助开发者理解其内部机制,包括动态SQL的解析、SQL映射文件与...
源码分析是理解框架工作原理的重要途径,通过阅读MyBatis的源码,我们可以深入学习其内部机制,包括SQL动态生成、结果映射、事务管理等方面。 1. SQL动态生成:MyBatis的核心之一是SQL动态语句。在XML配置文件或...
在分析MyBatis源码时,可以采用宏观和微观两种视角。宏观上理解整个框架的架构和流程,微观上深入到具体的类和方法,通过阅读和调试代码来理解其实现细节。同时,绘制流程图或UML图能帮助更好地梳理组件间的交互。 ...
Mapper接口和Mapper XML文件是MyBatis的另一个关键特性。通过`MapperRegistry`,MyBatis能将接口方法与XML中的SQL语句关联起来。在调用Mapper接口的方法时,MyBatis会根据方法名找到对应的SQL语句,并执行。 ...
根据提供的文件内容,我们可以展开关于Mybatis源码分析的详细知识点介绍。Mybatis是一个流行的Java持久层框架,它用于简化与数据库交互的复杂性。源码分析是理解框架内部工作原理的绝佳方式,同时也能够加深对设计...
《Mybatis源码分析》 在Java开发领域,Mybatis作为一个优秀的持久层框架,深受开发者喜爱。它将SQL语句与Java代码分离,提供了一种灵活的映射机制,使得数据库操作变得更加简单。本文将深入探讨Mybatis的核心原理,...
2. **MyBatis源码解析**: `mybatis-2.3.5-sources.jar`包含了MyBatis的源代码,这对于我们理解框架内部工作流程极其有价值。例如,你可以看到`SqlSession`、`SqlSessionFactory`和`Mapper`接口的实现,以及如何...
深入理解MyBatis源码,有助于我们了解其执行流程,比如:当执行一个Mapper接口的方法时,MyBatis是如何定位到对应的SQL,如何处理参数,如何映射结果,以及如何执行SQL并返回结果。这对于优化数据库操作、调试问题...
### Mybatis源码分析 #### 1. 解析配置文件,创建SQLSessionFactory 在MyBatis框架中,创建`SQLSessionFactory`是初始化整个框架的重要步骤之一。这一过程涉及到了配置文件的读取与解析,以及如何构建出可以用于...
本文将围绕"springBoot整合mybatis源码"的主题,详细阐述整合步骤、关键配置以及核心组件。 1. **Spring Boot与MyBatis的整合基础** - **自动配置**:Spring Boot的核心特性之一是自动配置,它能根据项目中的依赖...