mybatis :无参构造器在resultMap中的作用

resultMap ,association collection 分别根据 type javaType ofType指定的类型来创建相应的实例对象,创建实例对象是根据实体类的无参构造方法。所以说,要使用resultMap,association collection 必须要对应的实体类添加零参构造方法。否则,就会出现错误。


<mapper namespace="com.wang.demo.mapper.StudentMapper">
    <resultMap id="studentMap" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname" />
        <association property="teacher" javaType="Teacher">
            <result property="id" column="tid"/>
            <result property="name" column="tname"/>
            <result property="age" column="tage"/>
        </association>
    </resultMap>
      <select id="select" resultMap="studentMap">
          select  s.id as sid,s.name as sname,t.id as tid,t.name as tname,t.age as tage  from student as s, teacher as t where s.id=#{id} and s.teacher_id=t.id;
      </select>
</mapper>

resultMap对应的实体类没有无参构造:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Error instantiating class com.wang.demo.pojo.Student with invalid types (Long,String,Teacher) or values (1,wang,1). Cause: java.lang.IllegalArgumentException: argument type mismatch

association没有无参构造:

org.springframework.dao.DataIntegrityViolationException: Error attempting to get column 'sname' from result set.  Cause: java.sql.SQLDataException: Cannot determine value type from string 'wang'
; Cannot determine value type from string 'wang'; nested exception is java.sql.SQLDataException: Cannot determine value type from string 'wang'

总结:

无参构造在mybatis中地位很特殊,mybatis很多都是通过反射,通过无参构造注入的。因此当遇到错误说类不匹配,或字段不匹配时,检查有没有无参构造

posted @ 2021-10-06 22:07  刚刚好。  阅读(150)  评论(0编辑  收藏  举报