username为什么也能映射到userName上?

Mybatis resultType 字段映射(一)

一、前言

编写Mybatis XML SQL脚本,返回结果方式为resultType时,数据库字段username也能映射到Java Bean中的userName上

二、原理解析

  • resultType 字段映射调用链

=>org.apache.ibatis.executor.statement.PreparedStatementHandler#query

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#handleResultSets

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#handleResultSet

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#handleRowValues

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#handleRowValuesForSimpleResultMap

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#getRowValue(org.apache.ibatis.executor.resultset.ResultSetWrapper, org.apache.ibatis.mapping.ResultMap, java.lang.String)

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyAutomaticMappings

=>org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyAutomaticMappings

重点

=>org.apache.ibatis.reflection.MetaObject#findProperty

=>org.apache.ibatis.reflection.wrapper.BeanWrapper#findProperty

①所谓的“驼峰转换”就是去除下划线,usernameuser_name处理后的结果均为username

  public String findProperty(String name, boolean useCamelCaseMapping) {
    if (useCamelCaseMapping) {
      name = name.replace("_", "");
    }
    return findProperty(name);
  }

=>org.apache.ibatis.reflection.MetaClass#buildProperty

=>org.apache.ibatis.reflection.Reflector#findPropertyName

经过①处理后的结果转大写USERNAME作为key查找Java Bean中的属性;org.apache.ibatis.reflection.Reflector#Reflector构造函数中也是将Java Bean中的属性大写作为key,这就解释了为什么username也能映射到Java Bean中的userName上去了

 public String findPropertyName(String name) {
    return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH));
  }
  • Reflector初始化过程

=> com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration#sqlSessionFactory

=>com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean#buildSqlSessionFactory

=>com.baomidou.mybatisplus.core.MybatisXMLConfigBuilder#parseConfiguration

=>com.baomidou.mybatisplus.core.MybatisXMLConfigBuilder#settingsAsProperties

=>org.apache.ibatis.reflection.MetaClass#MetaClass

=>org.apache.ibatis.reflection.DefaultReflectorFactory#findForClass

你可能感兴趣的:(#,mybatis,问题汇总,#,源码分析,mybatis,java)