在练习mybatis的CRUD的时候遇见了错误:Result Maps collection does not contain value for…
Caused by: java.lang.IllegalArgumentException: Result Maps collection does not contain value for com.lh.dao.TeacherMapper.TeacherMapat org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:964)at org.apache.ibatis.session.Configuration.getResultMap(Configuration.java:674)at org.apache.ibatis.builder.MapperBuilderAssistant.getStatementResultMaps(MapperBuilderAssistant.java:339)... 16 more
原因:
在 xml 中使用了 resultMap 而没有配置 resultMap 标签。
<resultMap type="Teacher" id="TeacherMap"><!-- id标签对应主键 --><id property="id" column="id"/><!-- 类的普通属性对应表的普通字段使用result标签 --><result property="name" column="name"/></resultMap>
配置后就可以正常使用。
总结:
在做查询时,当实体类的属性名和数据库表的字段名不一致时,可以使用resultMap
来结果映射。
<!-- id必须唯一,type是结果集映射的表对应的实体类的全路径 --><resultMap type="Teacher" id="TeacherMap"><!-- id标签对应主键 --><id property="id" column="id"/><!-- 类的普通属性对应表的普通字段使用result标签 --><result property="name" column="name"/></resultMap>
resultMap是配置类的属性与表的字段对应的关系。它可以只配置需要的部分。resultMap可以配置多个,但是id不能重复。在做查询的时候,不是必须使用实体类或实体类的resultMap。还可以直接使用map集合若以后要多次使用查询,结果经常被其它地方使用,这种情况下还是要写实体类。
在执行一次性查询时,可以用Map。
<select id="selectById03" resultType="Map" parameterType="Integer">select * from student where id = #{id};</select><!-- 这个映射器对应的接口的方法,返回值是List<Map> --><select id="selectStu02" resultType="Map" >select * from student ;</select>