Mybatis字段映射实体,出现实体属性映射不上为null的情况

问题描述 :该条sql语句在mysql执行,class_name字段有值,但是在Student实体类中的className属性值为null,数据库查询的值没有映射进去className属性

  <resultMap id="StudentMap" type="com.qw.Student">
            <result property="code" column="code" jdbcType="VARCHAR"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
            <result property="className" column="class_name" jdbcType="VARCHAR"/>
        </resultMap>

        <select id="query"  resultType="com.qw.Student" resultMap="StudentMap">
            select s.code , s.name , c.class_name from bd_student s
            left join bd_class c on s.class_id = c.id
        </select>

解决方式:将c.class_name起别名 ,这个时候Student类的className属性就有值了。(不知道为什么以前从来没遇到过这种情况,s.code 和 s.name 也是没有别名,但是实体类里面确有值。以前最多可能是1.实体类忘记加setxxx()方法 2. resultMap标签忘记加这个需要的属性 3.select语句忘记引入resultMap标签)

<resultMap id="StudentMap" type="com.qw.Student">
            <result property="code" column="code" jdbcType="VARCHAR"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
            <result property="className" column="class_name" jdbcType="VARCHAR"/>
        </resultMap>

        <select id="query"  resultType="com.qw.Student" resultMap="StudentMap">
            select s.code , s.name , c.class_name as class_name from bd_student s
            left join bd_class c on s.class_id = c.id
        </select>

以后最好的方法避免这种问题,给所有的别名.字段加上别名如下:

<resultMap id="StudentMap" type="com.qw.Student">
            <result property="code" column="code" jdbcType="VARCHAR"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
            <result property="className" column="class_name" jdbcType="VARCHAR"/>
        </resultMap>

        <select id="query"  resultType="com.qw.Student" resultMap="StudentMap">
           select s.code as code , s.name as nam , c.class_name as class_name from bd_student s
           left join bd_class c on s.class_id = c.id
        </select>

你可能感兴趣的:(java,sql,开发语言)