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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬山境KL攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值