最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Mybatis遇到的there is no getter異常

 更新時(shí)間:2018年09月13日 09:40:16   作者:Somersames  
這篇文章主要介紹了使用Mybatis遇到的there is no getter異常,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

在使用mybatis的時(shí)候有時(shí)候會(huì)遇到一個(gè)問題就是明明參數(shù)是正確的,但是還是會(huì)提示There is no getter XXX這個(gè)異常,但是一般的解決辦法是在mapper里面添加@Param注解來完成是別的,那么為什么會(huì)遇到這個(gè)問題呢?

以下為舉例代碼:

Mapper層代碼
public interface Pro1_Mapper {

  Pro1_Studnet insertStu(Pro1_Studnet pro1_studnet);

}
實(shí)體類代碼
public class Pro1_Studnet {

  private String stuId;

  private String stuName;

  private String stuClass;

  private String stuTeacher;

  public String getStuId() {
    return stuId;
  }

  public void setStuId(String stuId) {
    this.stuId = stuId;
  }

  public String getStuName() {
    return stuName;
  }

  public void setStuName(String stuName) {
    this.stuName = stuName;
  }

  public String getStuClass() {
    return stuClass;
  }

  public void setStuClass(String stuClass) {
    this.stuClass = stuClass;
  }

  public String getStuTeacher() {
    return stuTeacher;
  }

  public void setStuTeacher(String stuTeacher) {
    this.stuTeacher = stuTeacher;
  }
}
Main方法
public static void main(String[] args) {
    Logger logger = null;
    logger = Logger.getLogger(Pro1_Main.class.getName());
    logger.setLevel(Level.DEBUG);
    SqlSession sqlSession = null;
    try {
      sqlSession = study.mybatis.MybatisUtil.getSqlSessionFActory().openSession();
      Pro1_Mapper pro1_Mapper = sqlSession.getMapper(Pro1_Mapper.class);
      Pro1_Studnet pro1_studnet =new Pro1_Studnet();
      pro1_studnet.setStuName("張三");
      Pro1_Studnet pro1_studnet1 =pro1_Mapper.insertStu(pro1_studnet);
      System.out.println(pro1_studnet1.getStuClass());
      sqlSession.commit();
    } finally {
      sqlSession.close();
    }
  }
XML文件
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="study.szh.demo.project1.Pro1_Mapper">
  <resultMap type="study.szh.demo.project1.Pro1_Studnet" id="pro1_stu">
    <result property="stuId" column="stu_id"/>
    <result property="stuName" column="stu_name"/>
    <result property="stuClass" column="stu_class"/>
    <result property="stuTeacher" column="stu_teacher"/>
  </resultMap>
  <select id="insertStu" parameterType="study.szh.demo.project1.Pro1_Studnet" resultMap="pro1_stu">
    SELECT * from pro_1stu where stu_name = #{pro1_studnet.stuName};
  </select>
</mapper>

如果執(zhí)行上述的代碼,你會(huì)發(fā)現(xiàn)mybatis會(huì)拋出一個(gè)異常:
There is no getter for property named 'pro1_studnet' in 'class study.szh.demo.project1.Pro1_Studnet'
很明顯就是說pro1_studnet這個(gè)別名沒有被mybatis正確的識(shí)別,那么將這個(gè)pro1_studnet去掉呢?

嘗試將xml文件中的pro1_studnet去掉然后只保留stuName,執(zhí)行代碼:

張三

這表明程序運(yùn)行的十分正常,但是在實(shí)際的寫法中,還有如果參數(shù)為String也會(huì)導(dǎo)致拋出getter異常,所以此次正好來分析下

分析

mybatis是如何解析mapper參數(shù)的

跟蹤源碼你會(huì)發(fā)現(xiàn)在MapperProxyinvoke處會(huì)進(jìn)行入?yún)?

@Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  try {
   if (Object.class.equals(method.getDeclaringClass())) {
    return method.invoke(this, args);
   } else if (isDefaultMethod(method)) {
    return invokeDefaultMethod(proxy, method, args);
   }
  } catch (Throwable t) {
   throw ExceptionUtil.unwrapThrowable(t);
  }
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
 }

注意此處的args,這個(gè)參數(shù)就是mapper的入?yún)ⅰ?br />

那么mybatis在這里接收到這個(gè)參數(shù)之后,它會(huì)將參數(shù)再一次進(jìn)行傳遞,此時(shí)會(huì)進(jìn)入到MapperMethodexecute方法

public Object execute(SqlSession sqlSession, Object[] args) {
  //省略無關(guān)代碼
   case SELECT:
    if (method.returnsVoid() && method.hasResultHandler()) {
     executeWithResultHandler(sqlSession, args);
     result = null;
    } else if (method.returnsMany()) {
     result = executeForMany(sqlSession, args);
    } else if (method.returnsMap()) {
     result = executeForMap(sqlSession, args);
    } else if (method.returnsCursor()) {
     result = executeForCursor(sqlSession, args);
    } else {
     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());
  }
  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;
 }

因?yàn)樵?code>xml文件里面使用的是select標(biāo)簽,所以會(huì)進(jìn)入case的select,然后此時(shí)會(huì)進(jìn)入到Object param = method.convertArgsToSqlCommandParam(args); 在這里args還是Stu的實(shí)體類,并未發(fā)生變化

隨后進(jìn)入convertArgsToSqlCommandParam方法,然后經(jīng)過一個(gè)方法的跳轉(zhuǎn),最后會(huì)進(jìn)入到ParamNameResolvergetNamedParams方法,

public Object getNamedParams(Object[] args) {
  final int paramCount = names.size();
  if (args == null || paramCount == 0) {
   return null;
  } else if (!hasParamAnnotation && paramCount == 1) {
   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()]);
    // add generic param names (param1, param2, ...)
    final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
    // ensure not to overwrite parameter named with @Param
    if (!names.containsValue(genericParamName)) {
     param.put(genericParamName, args[entry.getKey()]);
    }
    i++;
   }
   return param;
  }
 }

此時(shí)注意hasParamAnnotation這個(gè)判斷,這個(gè)判斷表示該參數(shù)是否含有標(biāo)簽,有的話在這里會(huì)在Map里面添加一個(gè)參數(shù),其鍵就是GENERIC_NAME_PREFIX(param) + i 的值。像在本次的測(cè)試代碼的話,會(huì)直接在return args[names.firstKey()];返回,不過這不是重點(diǎn),繼續(xù)往下走,會(huì)返回到MapperMethodexecute方法的這一行result = sqlSession.selectOne(command.getName(), param);

此時(shí)的param就是一個(gè)Stu對(duì)象了。

繼續(xù)走下去...由于mybatis的調(diào)用鏈太多,此處只會(huì)寫出需要注意的點(diǎn),可以在自己debug的時(shí)候稍微注意下。

BaseExecutorcreateCacheKey的方法

@Override
 public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
  if (closed) {
   throw new ExecutorException("Executor was closed.");
  }
  CacheKey cacheKey = new CacheKey();
  cacheKey.update(ms.getId());
  cacheKey.update(rowBounds.getOffset());
  cacheKey.update(rowBounds.getLimit());
  cacheKey.update(boundSql.getSql());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
  // mimic DefaultParameterHandler logic
  for (ParameterMapping parameterMapping : parameterMappings) {
   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);
    }
    cacheKey.update(value);
   }
  }
  if (configuration.getEnvironment() != null) {
   // issue #176
   cacheKey.update(configuration.getEnvironment().getId());
  }
  return cacheKey;
 }

當(dāng)進(jìn)行到這一步的時(shí)候,由于mybatis的類太多了,所以這里選擇性的跳過,當(dāng)然重要的代碼還是會(huì)介紹的。

DefaultReflectorFactory的findForClass方法

@Override
 public Reflector findForClass(Class<?> type) {
  if (classCacheEnabled) {
      // synchronized (type) removed see issue #461
   Reflector cached = reflectorMap.get(type);
   if (cached == null) {
    cached = new Reflector(type);
    reflectorMap.put(type, cached);
   }
   return cached;
  } else {
   return new Reflector(type);
  }
 }

注意MetaObjectgetValue方法:

 public Object getValue(String name) {
  PropertyTokenizer prop = new PropertyTokenizer(name);
  if (prop.hasNext()) {
   MetaObject metaValue = metaObjectForProperty(prop.getIndexedName());
   if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
    return null;
   } else {
    return metaValue.getValue(prop.getChildren());
   }
  } else {
   return objectWrapper.get(prop);
  }
 }

這里的name的值是pro1_stu.stuName,而prop的屬性是這樣的:


這里的hasNext函數(shù)會(huì)判斷這個(gè)prop的children是不是為空,如果不是空的話就會(huì)進(jìn)入 get 方法,然后進(jìn)入到如下的方法通過返回獲取get方法。

所以當(dāng)遍歷到stuName的時(shí)候會(huì)直接return,

然后就需要注意ReflectorgetGetInvoker方法,

public Invoker getGetInvoker(String propertyName) {
  Invoker method = getMethods.get(propertyName);
  if (method == null) {
   throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'");
  }
  return method;
 }

這個(gè)propertyName就是pro1_studnet,而getMethods.get(propertyName);就是要通過反射獲取pro1_studnet方法,但是很明顯,這里是獲取不到的,所以此時(shí)就會(huì)拋出這個(gè)異常。

那么為什么加了@param注解之后就不會(huì)拋出異常呢

此時(shí)就需要注意MapWrapper類的get方法。

 @Override
 public Object get(PropertyTokenizer prop) {
  if (prop.getIndex() != null) {
   Object collection = resolveCollection(prop, map);
   return getCollectionValue(prop, collection);
  } else {
   return map.get(prop.getName());
  }
 }

在之前就說過,如果加了注解的話,map的結(jié)構(gòu)是{"param1","pro1_studnet","pro1_studnet",XXX對(duì)象},此時(shí)由于prop的index是null,所以會(huì)直接返回map的鍵值為pro1_studnet的對(duì)象。

而在DefaultReflectorFactoryfindForClass里面,由于所加載的實(shí)體類已經(jīng)包含了Pro1_Student,隨后在metaValue.getValue(prop.getChildren());的將stu_name傳入過去,就可以了獲取到了屬性的值了。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java 獲取用戶的MAC地址多種方法實(shí)例詳解

    java 獲取用戶的MAC地址多種方法實(shí)例詳解

    這篇文章主要介紹了JAVA實(shí)現(xiàn)獲取用戶的MAC地址的多種方法實(shí)例,需要的朋友可以參考下
    2017-04-04
  • SpringBoot項(xiàng)目運(yùn)行一段時(shí)間后自動(dòng)關(guān)閉的坑及解決

    SpringBoot項(xiàng)目運(yùn)行一段時(shí)間后自動(dòng)關(guān)閉的坑及解決

    這篇文章主要介紹了SpringBoot項(xiàng)目運(yùn)行一段時(shí)間后自動(dòng)關(guān)閉的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • mybatis分頁絕對(duì)路徑寫法過程詳解

    mybatis分頁絕對(duì)路徑寫法過程詳解

    這篇文章主要介紹了mybatis分頁絕對(duì)路徑寫法過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Maven訪問倉庫順序代碼實(shí)例解析

    Maven訪問倉庫順序代碼實(shí)例解析

    這篇文章主要介紹了Maven訪問倉庫順序?qū)嵗馕?文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • 解決HttpPost+json請(qǐng)求---服務(wù)器中文亂碼及其他問題

    解決HttpPost+json請(qǐng)求---服務(wù)器中文亂碼及其他問題

    這篇文章主要介紹了解決HttpPost+json請(qǐng)求---服務(wù)器中文亂碼及其他問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • MybatisPlus 連表查詢、邏輯刪除功能實(shí)現(xiàn)(多租戶)

    MybatisPlus 連表查詢、邏輯刪除功能實(shí)現(xiàn)(多租戶)

    這篇文章主要介紹了MybatisPlus 連表查詢、邏輯刪除功能實(shí)現(xiàn)(多租戶),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-12-12
  • java對(duì)接支付寶支付接口簡(jiǎn)單步驟記錄

    java對(duì)接支付寶支付接口簡(jiǎn)單步驟記錄

    最近項(xiàng)目APP需要接入微信、支付寶支付功能,在分配開發(fā)任務(wù)時(shí),聽說微信支付接口比支付寶支付接口要難實(shí)現(xiàn),這篇文章主要給大家介紹了關(guān)于java對(duì)接支付寶支付接口的簡(jiǎn)單步驟,需要的朋友可以參考下
    2024-05-05
  • SparkSQL開窗函數(shù)分析使用示例

    SparkSQL開窗函數(shù)分析使用示例

    開窗函數(shù)的引入是為了既顯示聚集前的數(shù)據(jù),又顯示聚集后的數(shù)據(jù)。即在每一行的最后一列添加聚合函數(shù)的結(jié)果。開窗用于為行定義一個(gè)窗口,它對(duì)一組值進(jìn)行操作,不需要使用 GROUP BY 子句對(duì)數(shù)據(jù)進(jìn)行分組,能夠在同一行中同時(shí)返回基礎(chǔ)行的列和聚合列
    2023-01-01
  • Spring動(dòng)態(tài)代理實(shí)現(xiàn)日志功能詳解

    Spring動(dòng)態(tài)代理實(shí)現(xiàn)日志功能詳解

    這篇文章主要為大家詳細(xì)介紹了Spring動(dòng)態(tài)代理實(shí)現(xiàn)日志功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • JavaBean和Map轉(zhuǎn)換封裝類的方法

    JavaBean和Map轉(zhuǎn)換封裝類的方法

    下面小編就為大家?guī)硪黄狫avaBean和Map轉(zhuǎn)換封裝類的方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-10-10

最新評(píng)論

句容市| 平果县| 南召县| 平定县| 青浦区| 林西县| 琼结县| 绥德县| 华坪县| 乐陵市| 乡城县| 绥阳县| 永嘉县| 东山县| 肥乡县| 丹巴县| 安徽省| 积石山| 阳谷县| 阳高县| 衡山县| 河北省| 宝丰县| 布尔津县| 治多县| 沅陵县| 榆林市| 聂拉木县| 邵阳市| 武隆县| 搜索| 东海县| 醴陵市| 板桥市| 靖江市| 柘荣县| 西林县| 正安县| 自治县| 大名县| 化隆|