MyBatis测试报错:Cannot determine value type from string 'xxx'的解决办法

这篇文章主要给大家介绍了关于MyBatis测试报错:Cannot determine value type from string 'xxx'的解决办法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下

关于[Cannot determine value type from string ‘xxx’]的问题

1、产生

实体类Student中属性有id,name,email,age,未使用无参构造器

在mapper.xml中只查询name,email,age

测试时报错

Cannot determine value type from string '张三'

2、解决

实体类Student中添加无参构造器

得到结果

Student{id=null, name='张三', email='zhangsan@126.com', age=22}

3、探究

跟踪源码

org.apache.ibatis.executor.resultset.DefaultResultSetHandler

这个类有个方法createResultObject

private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List constructorMappings = resultMap.getConstructorResultMappings(); if (hasTypeHandlerForResultObject(rsw, 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); } throw new ExecutorException("Do not know how to create an instance of " + resultType); } 

这个方法是根据结果集返回值的类型创建出相应的bean字段对象

  • 当实体使用无参构造器时

mybatis会调用createResultObject方法中objectFactory.create(resultType),使用无参构造器创建对象

private   T instantiateClass(Class type, List

​ 这个代码片段里面有个TypeHandler,这个是mybatis的类型处理器,用来处理 JavaType 与 JdbcType 之间的转换。

由代码我们看出,当实体使用有参构造函数时,会遍历有参构造参数个数,根据有参构造参数下标 查找相应的数据库字段名称,根据有参构造字段类型以及数据库字段名称找类型处理器。然后使用TypeHandler来处理JavaType 与 JdbcType 之间的转换。当转换异常,就会报错

4、总结

解决Cannot determine value type from string 'xxx’的方法有2种

  • 实体加无参构造参数
  • mapper.xml中查询的数据库字段属性的类型要和有参构造器的字段类型一一匹配;查询字段的个数要和有参构造器个数一样

到此这篇关于MyBatis测试报错:Cannot determine value type from string 'xxx'解决的文章就介绍到这了,更多相关Cannot determine value type from string内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是MyBatis测试报错:Cannot determine value type from string 'xxx'的解决办法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java