解决org.apache.ibatis.executor.ExecutorException: No constructor found in xxxBean问题

在使用mybatis时遇到该问题,解决方法很简单,在实体类bean中加一个无参的构造方法即可,具体原因如下:

相关源码如下:

private Object createByConstructorSignature(ResultSetWrapper rsw, Class resultType, List> constructorArgTypes, List constructorArgs,
      String columnPrefix) throws SQLException {
    for (Constructor constructor : resultType.getDeclaredConstructors()) {
      if (typeNames(constructor.getParameterTypes()).equals(rsw.getClassNames())) {
        boolean foundValues = false;
        for (int i = 0; i < constructor.getParameterTypes().length; i++) {
          Class parameterType = constructor.getParameterTypes()[i];
          String columnName = rsw.getColumnNames().get(i);
          TypeHandler typeHandler = rsw.getTypeHandler(parameterType, columnName);
          Object value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(columnName, columnPrefix));
          constructorArgTypes.add(parameterType);
          constructorArgs.add(value);
          foundValues = value != null || foundValues;
        }
        return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
      }
    }
    throw new ExecutorException("No constructor found in " + resultType.getName() + " matching " + rsw.getClassNames());
  } 
  

从上述代码可以看出当创建对象来接受sql结果时会遍历实体类的构造方法找到与之匹配的,如果实体类中有构造方法了但是参数不匹配的话就会报上述错误,此时添加无参构造方法(默认的构造方法),会走其他方法,具体代码如下:

private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List> constructorArgTypes, List constructorArgs, String columnPrefix)
      throws SQLException {
    final Class resultType = resultMap.getType();
    final MetaClass metaType = MetaClass.forClass(resultType, reflectorFactory);
    final List constructorMappings = resultMap.getConstructorResultMappings();
    if (typeHandlerRegistry.hasTypeHandler(resultType)) {
      return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
    } else if (!constructorMappings.isEmpty()) {
      return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs, columnPrefix);
    } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {//有无参构造方法时走这里
      return objectFactory.create(resultType);
    } else if (shouldApplyAutomaticMappings(resultMap, false)) {//有构造方法但无默认构造方法
      return createByConstructorSignature(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix);
    }
    throw new ExecutorException("Do not know how to create an instance of " + resultType);
  } 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(mybatis)