Mybatis源码解析之查询流程
2018-01-20 16:17
543 查看
阅读须知
Mybatis源码版本:3.4.4注释规则:
//单行注释做普通注释
/**/多行注释做深入分析
建议配合Mybatis源码阅读
正文
上篇文章中我们分析mapper的创建,Mybatis用JDK动态代理为mapper创建代理类,其中MapperProxy作为InvocationHandler角色,所以调用目标mapper方法时会执行其invoke方法,我们来分析MapperProxy的invoke方法:public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) { //如果是从Object继承的方法,直接执行 return method.invoke(this, args); //判断是否是默认方法,默认方法是Java8的新特性,判断逻辑与Java8 Method类的isDefault方法一样 } else if (isDefaultMethod(method)) { //调用默认方法,这里面用到了Java7的API,有兴趣的读者可以自行了解 return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } /*构建并缓存MapperMethod*/ final MapperMethod mapperMethod = cachedMapperMethod(method); /*执行*/ return mapperMethod.execute(sqlSession, args); }
MapperProxy:
private MapperMethod cachedMapperMethod(Method method) { MapperMethod mapperMethod = methodCache.get(method); if (mapperMethod == null) { /*构造MapperMethod*/ mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()); methodCache.put(method, mapperMethod); } return mapperMethod; }
MapperMethod:
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) { /*构造sql命令对象*/ this.command = new SqlCommand(config, mapperInterface, method); /*构造方法签名对象*/ this.method = new MethodSignature(config, mapperInterface, method); }
MapperMethod.SqlCommand:
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) { final String methodName = method.getName(); final Class<?> declaringClass = method.getDeclaringClass(); /*解析获取MappedStatement*/ MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass, configuration); if (ms == null) { if (method.getAnnotation(Flush.class) != null) { name = null; type = SqlCommandType.FLUSH; } else { throw new BindingException("Invalid bound statement (not found): " + mapperInterface.getName() + "." + methodName); } } else { //将MappedStatement的相关属性复制给当前对象的相关属性 name = ms.getId(); type = ms.getSqlCommandType(); if (type == SqlCommandType.UNKNOWN) { throw new BindingException("Unknown execution method for: " + name); } } }
MapperMethod.SqlCommand:
private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName, Class<?> declaringClass, Configuration configuration) { //拼接statementId String statementId = mapperInterface.getName() + "." + methodName; if (configuration.hasStatement(statementId)) { //如果configuration对象中包含相应MappedStatement对象,直接返回 return configuration.getMappedStatement(statementId); } else if (mapperInterface.equals(declaringClass)) { //如果方法所属Class与mapper接口Class是相同的,直接返回null return null; } for (Class<?> superInterface : mapperInterface.getInterfaces()) { //遍历mapper接口类的父接口,如果与方法所属Class相同或者是其子接口,递归获取MappedStatement对象 if (declaringClass.isAssignableFrom(superInterface)) { MappedStatement ms = resolveMappedStatement(superInterface, methodName, declaringClass, configuration); if (ms != null) { return ms; } } } return null; }
MapperMethod.MethodSignature:
public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) { /*解析返回值类型*/ Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface); if (resolvedReturnType instanceof Class<?>) { this.returnType = (Class<?>) resolvedReturnType; } else if (resolvedReturnType instanceof ParameterizedType) { this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType(); } else { this.returnType = method.getReturnType(); } //声明返回值是否是void类型 this.returnsVoid = void.class.equals(this.returnType); //声明返回值是否是集合或者数组这种多值类型 this.returnsMany = (configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray()); this.returnsCursor = Cursor.class.equals(this.returnType); //如果方法返回值是Map类型则判断方法上是否注解了@MapKey并获取其value属性值返回 this.mapKey = getMapKey(method); this.returnsMap = (this.mapKey != null); //如果方法参数中包含RowBounds类型或其子类型的参数,找出这个参数在方法参数列表中的下标值 this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class); //如果方法参数中包含ResultHandler类型或其子类型的参数,找出这个参数在方法参数列表中的下标值 this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class); /*声明参数名称解析器*/ this.paramNameResolver = new ParamNameResolver(configuration, method); }
TypeParameterResolver:
public static Type resolveReturnType(Method method, Type srcType) { Type returnType = method.getGenericReturnType(); Class<?> declaringClass = method.getDeclaringClass(); /*解析类型*/ return resolveType(returnType, srcType, declaringClass); }
TypeParameterResolver:
private static Type resolveType(Type type, Type srcType, Class<?> declaringClass) { if (type instanceof TypeVariable) { //解析泛型的类型变量,TypeVariable可以获取到声明的泛型的名称、声明此泛型的类型、泛型的上下限信息等 return resolveTypeVar((TypeVariable<?>) type, srcType, declaringClass); } else if (type instanceof ParameterizedType) { //解析泛型的类型信息,ParameterizedType可以获取到声明的泛型的类型信息 return resolveParameterizedType((ParameterizedType) type, srcType, declaringClass); } else if (type instanceof GenericArrayType) { //解析数组类型的泛型信息 return resolveGenericArrayType((GenericArrayType) type, srcType, declaringClass); } else { return type; } }
关于上面出现的这几种Type类型的说明,可以参见文末的参考链接。
ParamNameResolver:
public ParamNameResolver(Configuration config, Method method) { final Class<?>[] paramTypes = method.getParameterTypes(); //方法参数列表 final Annotation[][] paramAnnotations = method.getParameterAnnotations(); //参数的注解信息 final SortedMap<Integer, String> map = new TreeMap<Integer, String>(); int paramCount = paramAnnotations.length; for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) { /*特殊参数忽略*/ if (isSpecialParameter(paramTypes[paramIndex])) { continue; } String name = null; for (Annotation annotation : paramAnnotations[paramIndex]) { if (annotation instanceof Param) { hasParamAnnotation = true; //如果参数注解了@Param,获取注解的value属性值 name = ((Param) annotation).value(); break; } } if (name == null) { //默认为true,可以配置 if (config.isUseActualParamName()) { //反射获取参数的真实名称 name = getActualParamName(method, paramIndex); } if (name == null) { //如果没有办法加载java.lang.reflect.Parameter字节码,name就可能为null,这时用参数的下标作为name name = String.valueOf(map.size()); } } map.put(paramIndex, name); //下标和name做映射 } names = Collections.unmodifiableSortedMap(map); }
ParamNameResolver:
private static boolean isSpecialParameter(Class<?> clazz) { return RowBounds.class.isAssignableFrom(clazz) || ResultHandler.class.isAssignableFrom(clazz); }
特殊参数就是RowBounds或ResultHandler类型的参数。构建好MapperMethod后,调用其execute方法执行:
public Object execute(SqlSession sqlSession, Object[] args) { Object result; switch (command.getType()) { case INSERT: { /*将参数转换为sql命令的参数*/ Object param = method.convertArgsToSqlCommandParam(args); /*插入,返回影响行数的结果*/ result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { /*将参数转换为sql命令的参数*/ Object param = method.convertArgsToSqlCommandParam(args); /*更新,返回影响行数的结果*/ result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { /*将参数转换为sql命令的参数*/ Object param = method.convertArgsToSqlCommandParam(args); /*删除,返回影响行数的结果*/ result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: //下面几个分支判断的条件,我们在分析构造MapperMethod的过程时看到了这些波尔条件的赋值过程 if (method.returnsVoid() && method.hasResultHandler()) { /*返回void并且方法包含ResultHandler的查询的执行*/ executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) { /*多个返回值的查询的执行*/ result = executeForMany(sqlSession, args); } else if (method.returnsMap()) { /*@MapKey注解的Map类型的返回值的查询的执行*/ result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) { /*Cursor游标类型的返回值的查询的执行*/ result = executeForCursor(sqlSession, args); } else { /*将参数转换为sql命令的参数*/ Object param = method.convertArgsToSqlCommandParam(args); /*单个返回值的查询的执行*/ result = sqlSession.selectOne(command.getName(), param); } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } //命令执行结果为null,并且方法返回值是基本类型抛出异常 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; }
下面我们来逐个分析各种返回类型的查询的执行流程:
private void executeWithResultHandler(SqlSession sqlSession, Object[] args) { MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(command.getName()); //使用ResultHandler作为方法参数,方法需要有@ResultMap或@ResultType注解,或者在mapper配置文件中定义了resultType属性 if (void.class.equals(ms.getResultMaps().get(0).getType())) { throw new BindingException("method " + command.getName() + " needs either a @ResultMap annotation, a @ResultType annotation," + " or a resultType attribute in XML so a ResultHandler can be used as a parameter."); } /*将参数转换为sql命令的参数*/ Object param = method.convertArgsToSqlCommandParam(args); if (method.hasRowBounds()) { //如果方法参数中包含RowBounds类型的参数,提取这个参数,构造MapperMethod时计算了RowBounds类型参数在方法参数列表的下标值 RowBounds rowBounds = method.extractRowBounds(args); /*提取ResultHandler类型的参数,携带RowBounds查询*/ sqlSession.select(command.getName(), param, rowBounds, method.extractResultHandler(args)); } else { /*提取ResultHandler类型的参数,不带RowBounds查询*/ sqlSession.select(command.getName(), param, method.extractResultHandler(args)); } }
MapperMethod:
public Object convertArgsToSqlCommandParam(Object[] args) { /*获取命名参数*/ return paramNameResolver.getNamedParams(args); }
ParamNameResolver:
public Object getNamedParams(Object[] args) { final int paramCount = names.size(); if (args == null || paramCount == 0) { return null; //解析的参数名称为空,返回null } else if (!hasParamAnnotation && paramCount == 1) { //没有注解@Param的参数并且解析的参数名称只有一个,根据下标返回参数 return args[names.firstKey()]; } else { final Map<String, Object> param = new ParamMap<Object>(); int i = 0; for (Map.Entry<Integer, String> entry : names.entrySet()) { //添加参数命名和参数值的对应关系 param.put(entry.getValue(), args[entry.getKey()]); //通用的参数名称,param1,param2... final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1); if (!names.containsValue(genericParamName)) { //添加通用参数名称和参数值的对应关系 param.put(genericParamName, args[entry.getKey()]); } i++; } return param; } }
DefaultSqlSession:
public void select(String statement, Object parameter, ResultHandler handler) { select(statement, parameter, RowBounds.DEFAULT, handler); }
没有RowBounds参数的select方法会用默认的RowBounds来调用重载的携带RowBounds参数的select方法。
DefaultSqlSession:
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) { try { //根据statementId获取MappedStatement MappedStatement ms = configuration.getMappedStatement(statement); /*包装集合类型的参数,调用执行器的相关方法查询*/ executor.query(ms, wrapCollection(parameter), rowBounds, handler); } catch (Exception e) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e); } finally { ErrorContext.instance().reset(); } }
DefaultSqlSession:
private Object wrapCollection(final Object object) { if (object instanceof Collection) { StrictMap<Object> map = new StrictMap<Object>(); map.put("collection", object); if (object instanceof List) { map.put("list", object); } return map; } else if (object != null && object.getClass().isArray()) { StrictMap<Object> map = new StrictMap<Object>(); map.put("array", object); return map; } return object; }
对集合类型参数的包装,就是如果参数是集合类型,会根据参数类型的不同为参数添加不同的key。我们在之前的分析看到,这里的executor在默认配置的情况下的类型是CachingExecutor:
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException { /*获取解析过动态标签的sql*/ BoundSql boundSql = ms.getBoundSql(parameterObject); //创建缓存key CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql); /*调用另一个重载的查询方法进行查询*/ return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
关于Mybatis缓存的内容我们会用单独的文章进行分析。
MappedStatement:
public BoundSql getBoundSql(Object parameterObject) { /*获取解析过动态标签的sql*/ BoundSql boundSql = sqlSource.getBoundSql(parameterObject); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings == null || parameterMappings.isEmpty()) { boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject); } //检查参数映射中是否存在嵌套的resultMap并设置boolean标记 for (ParameterMapping pm : boundSql.getParameterMappings()) { String rmId = pm.getResultMapId(); if (rmId != null) { ResultMap rm = configuration.getResultMap(rmId); if (rm != null) { hasNestedResultMaps |= rm.hasNestedResultMaps(); } } } return boundSql; }
在Mybatis标签解析的文章中我们看到,在创建SqlSource时,会根据解析标签时判断的是否是动态标签的结果来创建不同的SqlSource,这里我们以DynamicSqlSource为例进行分析:
public BoundSql getBoundSql(Object parameterObject) { DynamicContext context = new DynamicContext(configuration, parameterObject); //这里会根据动态标签的不同,如<if/>、<foreach/>等,解析这些节点拼接到sql中,会涉及到OGNL表达式解析的内容,有兴趣的读者可以自行了解 rootSqlNode.apply(context); SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration); Class<?> parameterType = parameterObject == null ? Object.class : parameterObject.getClass(); //将#{}替换成?号占位符,并构建每个占位符对应参数属性的映射 SqlSource sqlSource = sqlSourceParser.parse(context.getSql(), parameterType, context.getBindings()); //将解析内容封装到BoundSql对象中返回 BoundSql boundSql = sqlSource.getBoundSql(parameterObject); for (Map.Entry<String, Object> entry : context.getBindings().entrySet()) { boundSql.setAdditionalParameter(entry.getKey(), entry.getValue()); } return boundSql; }
CachingExecutor:
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { Cache cache = ms.getCache(); if (cache != null) { flushCacheIfRequired(ms); if (ms.isUseCache() && resultHandler == null) { ensureNoOutParams(ms, parameterObject, boundSql); @SuppressWarnings("unchecked") List<E> list = (List<E>) tcm.getObject(cache, key); if (list == null) { /*查询*/ list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); tcm.putObject(cache, key, list); } return list; } } /*查询*/ return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }
同样,我们先忽略缓存,继续分析查询的流程:
BaseExecutor:
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++; list = 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(); if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) { clearLocalCache(); } } return list; }
BaseExecutor:
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 { /*子类实现具体的查询逻辑*/ 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*/ StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql); /*准备Statement*/ stmt = prepareStatement(handler, ms.getStatementLog()); /*查询*/ return handler.<E>query(stmt, resultHandler); } finally { closeStatement(stmt); //关闭statement } }
Configuration:
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { /*构造RoutingStatementHandler*/ StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql); //拦截器执行 statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler); return statementHandler; }
RoutingStatementHandler:
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { //根据statementType配置选择不同的处理器,在标签解析时我们看到默认为PREPARED switch (ms.getStatementType()) { case STATEMENT: delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql); break; case PREPARED: delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql); break; case CALLABLE: delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql); break; default: throw new ExecutorException("Unknown statement type: " + ms.getStatementType()); } }
SimpleExecutor:
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException { Statement stmt; //获取数据库连接 Connection connection = getConnection(statementLog); /*准备Statement*/ stmt = handler.prepare(connection, transaction.getTimeout()); /*为Statement设置参数*/ handler.parameterize(stmt); return stmt; }
RoutingStatementHandler:
public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException { return delegate.prepare(connection, transactionTimeout); }
BaseStatementHandler:
public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException { ErrorContext.instance().sql(boundSql.getSql()); Statement statement = null; try { /*实例化Statement*/ statement = instantiateStatement(connection); /*设置超时时间*/ setStatementTimeout(statement, transactionTimeout); /*设置FetchSize*/ setFetchSize(statement); return statement; } catch (SQLException e) { closeStatement(statement); //异常关闭Statement throw e; } catch (Exception e) { closeStatement(statement); //异常关闭Statement throw new ExecutorException("Error preparing statement. Cause: " + e, e); } }
PreparedStatementHandler:
protected Statement instantiateStatement(Connection connection) throws SQLException { String sql = boundSql.getSql(); if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) { String[] keyColumnNames = mappedStatement.getKeyColumns(); if (keyColumnNames == null) { return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(sql, keyColumnNames); } } else if (mappedStatement.getResultSetType() != null) { return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY); } else { return connection.prepareStatement(sql); } }
实例化Statement就是根据配置不同调用Connection的不同重载方法来创建PreparedStatement,具体每个重载的方法的作用,请参考Java API。
BaseStatementHandler:
protected void setStatementTimeout(Statement stmt, Integer transactionTimeout) throws SQLException { Integer queryTimeout = null; //标签上配置的timeout优先级最高 if (mappedStatement.getTimeout() != null) { queryTimeout = mappedStatement.getTimeout(); } else if (configuration.getDefaultStatementTimeout() != null) { //标签没有配置则应用全局配置的timeout queryTimeout = configuration.getDefaultStatementTimeout(); } if (queryTimeout != null) { stmt.setQueryTimeout(queryTimeout); } /*应用事务超时时间*/ StatementUtil.applyTransactionTimeout(stmt, queryTimeout, transactionTimeout); }
StatementUtil:
public static void applyTransactionTimeout(Statement statement, Integer queryTimeout, Integer transactionTimeout) throws SQLException { if (transactionTimeout == null){ return; } Integer timeToLiveOfQuery = null; //没有配置查询超时时间则应用事务配置的超时时间 if (queryTimeout == null || queryTimeout == 0) { timeToLiveOfQuery = transactionTimeout; } else if (transactionTimeout < queryTimeout) { //如果事务配置的超时时间小于配置的查询超时时间,则应用事务配置的超时时间 timeToLiveOfQuery = transactionTimeout; } if (timeToLiveOfQuery != null) { statement.setQueryTimeout(timeToLiveOfQuery); } }
BaseStatementHandler:
protected void setFetchSize(Statement stmt) throws SQLException { //标签上配置的优先 Integer fetchSize = mappedStatement.getFetchSize(); if (fetchSize != null) { stmt.setFetchSize(fetchSize); return; } Integer defaultFetchSize = configuration.getDefaultFetchSize(); if (defaultFetchSize != null) { //标签上没有配置则使用全局配置 stmt.setFetchSize(defaultFetchSize); } }
RoutingStatementHandler:
public void parameterize(Statement statement) throws SQLException { /*为Statement设置参数*/ delegate.parameterize(statement); }
PreparedStatementHandler:
public void parameterize(Statement statement) throws SQLException { /*为Statement设置参数*/ parameterHandler.setParameters((PreparedStatement) statement); }
DefaultParameterHandler:
public void setParameters(PreparedStatement ps) { ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings != null) { //遍历参数绑定映射列表 for (int i = 0; i < parameterMappings.size(); i++) { ParameterMapping parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; //获取参数绑定的属性名称 String propertyName = parameterMapping.getProperty(); if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); //根据属性名称从参数对象中反射获取对应的值 value = metaObject.getValue(propertyName); } //获取类型处理器 TypeHandler typeHandler = parameterMapping.getTypeHandler(); //获取jdbcType类型 JdbcType jdbcType = parameterMapping.getJdbcType(); if (value == null && jdbcType == null) { jdbcType = configuration.getJdbcTypeForNull(); } try { /*为PreparedStatement设置值*/ typeHandler.setParameter(ps, i + 1, value, jdbcType); } catch (TypeException e) { throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e); } catch (SQLException e) { throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e); } } } } }
BaseTypeHandler:
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { if (jdbcType == null) { throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters."); } try { //设置空值 ps.setNull(i, jdbcType.TYPE_CODE); } catch (SQLException e) { throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " + "Cause: " + e, e); } } else { try { //子类实现具体的非空值设置 setNonNullParameter(ps, i, parameter, jdbcType); } catch (Exception e) { throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different configuration property. " + "Cause: " + e, e); } } }
这里根据构建ParameterMapping时设置的TypeHandler来为PreparedStatement设置对应类型的值。
RoutingStatementHandler:
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException { /*查询*/ return delegate.<E>query(statement, resultHandler); }
PreparedStatementHandler:
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException { PreparedStatement ps = (PreparedStatement) statement; ps.execute(); //执行sql命令 /*处理结果集*/ return resultSetHandler.<E> handleResultSets(ps); }
查询结果集的处理我们会用单独的文章来分析,下面我们来看其他类型的查询:
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) { List<E> result; //将参数转换为sql命令的参数,已经分析过 Object param = method.convertArgsToSqlCommandParam(args); if (method.hasRowBounds()) { RowBounds rowBounds = method.extractRowBounds(args); //携带RowBounds类型参数的查询 result = sqlSession.<E>selectList(command.getName(), param, rowBounds); } else { //不带RowBounds类型参数的查询 result = sqlSession.<E>selectList(command.getName(), param); } //如果方法的返回值类型与返回结果的类型不同需要做转换 if (!method.getReturnType().isAssignableFrom(result.getClass())) { if (method.getReturnType().isArray()) { /*转换成数组*/ return convertToArray(result); } else { /*转换成声明的集合类型*/ return convertToDeclaredCollection(sqlSession.getConfiguration(), result); } } return result; }
这里的查询过程与我们上文分析的查询过程是一样的,不同的是这里的参数不携带ResultHandler。
MapperMethod:
private <E> Object convertToArray(List<E> list) { //获取数组组件类型的Class Class<?> arrayComponentType = method.getReturnType().getComponentType(); //创建与返回结果集同样大小的数组 Object array = Array.newInstance(arrayComponentType, list.size()); if (arrayComponentType.isPrimitive()) { for (int i = 0; i < list.size(); i++) { //如果是基本类型需要逐个设置值,因为集合的泛型不允许声明为基本类型 Array.set(array, i, list.get(i)); } return array; } else { //直接将集合转换成数组 return list.toArray((E[])array); } }
MapperMethod:
private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) { /*创建返回集合,objectFactory可以配置,默认为DefaultObjectFactory*/ Object collection = config.getObjectFactory().create(method.getReturnType()); MetaObject metaObject = config.newMetaObject(collection); //将结果集添加到返回集合中 metaObject.addAll(list); return collection; }
DefaultObjectFactory:
public <T> T create(Class<T> type) { /*创建返回集合/ return create(type, null, null); }
DefaultObjectFactory:
public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) { /*解析返回集合类型*/ Class<?> classToCreate = resolveInterface(type); //反射实例化返回集合 return (T) instantiateClass(classToCreate, constructorArgTypes, constructorArgs); }
DefaultObjectFactory:
protected Class<?> resolveInterface(Class<?> type) { Class<?> classToCreate; if (type == List.class || type == Collection.class || type == Iterable.class) { classToCreate = ArrayList.class; } else if (type == Map.class) { classToCreate = HashMap.class; } else if (type == SortedSet.class) { classToCreate = TreeSet.class; } else if (type == Set.class) { classToCreate = HashSet.class; } else { classToCreate = type; } return classToCreate; }
方法的目的就是根据返回集合的类型来确认实例化集合的类型。其他几种查询类型我们简单说明一下,就不一一详细分析了,查询流程都大同小异。executeForMap方法会用DefaultMapResultHandler对返回结果集合进行处理;Cursor游标查询也同样是对返回结果集的特殊处理,感兴趣的同学可以自行查阅资料进行学习;单条结果查询的流程与多值结果的查询流程相同,不同的是会校验返回结果集合的大小不能大于1,然后返回null或者取出集合中的单条记录。到这里,Mybatis查询流程的源码解析就完成了,下篇文章我们来分析Mybatis的写操作。
相关文章推荐
- mybatis源码解析 - 通过一个简单查询例子分析流程
- mybatis源码解析 - 通过一个简单查询例子分析流程
- Mybatis源码解析之写流程
- MyBatis源码解析(一)——执行流程
- Mybatis源码详解之接口方法被执行流程源码解析
- mybatis源码解析-----执行流程1
- mybatis源码解析以及执行的流程
- Mybatis实现【4】-查询解析(一次SQL查询的源码分析)
- Mybatis的源码与流程解析
- ES查询流程源码解析
- 关于Mybatis的$和#的细节,源码解析
- android源码解析(二十二)-->Toast加载绘制流程
- Mybatis源码(三)之SqlSession执行流程全貌
- Mybatis SqlSessionTemplate 源码解析
- Mybatis源码解析-MapperRegistry代理注册mapper接口
- Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource
- Android恢复出厂设置流程分析【Android源码解析十】
- Mybatis SqlSessionTemplate 源码解析
- MyBatis源码——解析MyBatis配置文件
- 安卓5.1源码解析 : RecyclerView解析 从绘制流程,ViewHolder复用机制,LayoutManger,ItemAnimator等流程全面讲解