Mybatis 源码分析

来源:互联网 发布:div加载完成后执行js 编辑:程序博客网 时间:2024/05/15 01:19
mybatis解析:


1、mybatis 的解析:从applicationContext.xml开始;
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
              <property name="basePackage" value="com.nk.flyboy.dao.mapper"></property>
     </bean>


 MapperScannerConfigurer 继承了BeanDefinitionRegistryPostProcessor 接口,在spring bean解析的 invokeBeanFactoryPostProcessors()方法中进行调用。mybaits会根据属性basePackage(多个包可以用;隔开)的值对对应的包进行扫描,将包中的(只有类型为接口的文件)class文件加载成BeanDefinition保存,最终生成的bean 使用了Java代理proxy。




2、 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource"></property>
              <property name="configLocation" value="classpath:MyBatis-Configuration.xml"></property>
              <property name="mapperLocations" value="classpath:SqlMapper/*.xml"></property>
       </bean>




  SqlSessionFactoryBean 继承了 InitializingBean 接口,在bean解析的finishBeanFactoryInitialization() 的方法对 InitializingBean接口中的 afterPropertiesSet()方法进行调用,初始化mybatis的sqlSessionFactory实例,包括以下动作:
  1)、解析configLocation属性,其中能包括 typeAliases,typeHandlers 等的解析
  2)、解析dataSource属性
  3)、解析mapperLocations属性,扫描对应路径下的XML文件并解析加载,保存到Configuration类中。




3、实际使用过程中,调用mapper接口中的方法时,实际是调用接口的代理proxy,invoke方法如下:


public <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);
    }
  }


  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);
  }


public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


//object类中的方法直接调用
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    //mapper接口的方法能够进行缓存,不用重复实例化
    final MapperMethod mapperMethod = cachedMapperMethod(method);


    //执行mapper接口对应的SQL操作
    return mapperMethod.execute(sqlSession, args);
  }


  private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      //实例化一个 mapperMethod
      //mapperMethod 包含两个属性 command 和 method
      // command 为 SqlCommand,属性 MappedStatement 包含了sqlSource 类,Configuration类,resultMaps类等。通过command实例可以得到要执行的SQL语句和参数
      // method 为MethodSignature,通过此类能解析出本方法要返回的类型等
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }




4、mybatis 比较两个字段名是否相同通过将两个字段名统一转换成大写后比较是否一致


5、mybatis IOC实现:


private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
    final ResultLoaderMap lazyLoader = new ResultLoaderMap();
    Object resultObject = createResultObject(rsw, resultMap, lazyLoader, null);
    if (resultObject != null && !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) {
      final MetaObject metaObject = configuration.newMetaObject(resultObject);
      boolean foundValues = !resultMap.getConstructorResultMappings().isEmpty();
      if (shouldApplyAutomaticMappings(resultMap, false)) {
        foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
      }
      foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
      foundValues = lazyLoader.size() > 0 || foundValues;
      resultObject = foundValues ? resultObject : null;
      return resultObject;
    }
    return resultObject;
  }


  private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
    final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
    boolean foundValues = false;
    for (String columnName : unmappedColumnNames) {
      String propertyName = columnName;
      if (columnPrefix != null && !columnPrefix.isEmpty()) {
        // When columnPrefix is specified,
        // ignore columns without the prefix.
        if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
          propertyName = columnName.substring(columnPrefix.length());
        } else {
          continue;
        }
      }
      final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
      if (property != null && metaObject.hasSetter(property)) {
        final Class<?> propertyType = metaObject.getSetterType(property);
        if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
          final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
          final Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
          // issue #377, call setter on nulls
          if (value != null || configuration.isCallSettersOnNulls()) {
            if (value != null || !propertyType.isPrimitive()) {
              metaObject.setValue(property, value);
            }
            foundValues = true;
          }
        }
      }
    }
    return foundValues;
  }




6、ResultHandler 用于处理返回的结果集,使用方法: void getUser(Integer id,UserResultHandler resultHandler)。注意方法的返回值一定得为 void 才能生效。