Mybatis-ResultMap

SELECT id,name,pwd FROM user WHERE id=#{id};

mybatis会自动创建一个ResultMap来映射结果集

例如User类中包含属性 id,name,pwd,则自动映射,都能对应上

但如果User类中的属性字段为id,name,password,查询出的结果password = null

解决办法

1、SQL语句字段起别名

        把对应的SQL语句改为

SELECT id,name,pwd as password FROM user WHERE id=#{id};

        但这并不是一种好方法

2、使用ResultMap结果集来映射

<!--mybatis配置文件中使用TypeAlias配置了别名-->
<resultMap id="userResultMap" Type="User">
    <!--column对应了数据库表中的字段名,property对应了实体类的属性名-->
    <result column="id" property="id" />
    <result column="name" property="name" />
    <result column="pwd" property="password" />
</resultMap>


3、如果需要查的字段不是基本数据类型,而是一个对象(多表联查)

        1)按照查询嵌套处理

<select id="getStudents" resultMap="StudentTeacher">
    select s.id,s.name,t.name from student s,teacher t where s.tid=t.id
</select>

<resultMap id="StudentTeacher" Type="Student">
    <!--字段是Student类的属性时-->
    <result column="id" property="id" />
    <result column="name" property="name" />

    <!--复杂的属性需要单独处理
        对象:association
        集合:collection
        子查询
    -->
    <association column="tid" property="teacher" javaType="Teacher" select="getTeacher"/>
</resultMap> 


<select id="getTeacher" resultType="Teacher">
    select * from teacher where tid=#{tid}
</select>

        2)按照结果嵌套处理

        多对一

<select id="getStudents" resultMap="StudentTeacher">
    select s.id as sid,s.name as sname,t.name as tname
    from student s,teacher t
    where s.tid=t.id
</select>

<resultMap id="StudentTeacher" type="Student">
    <result column="sid" property="id" />
    <result column="sname" property="name" />

    <association property="teacher" javaType="Teacher">
        <result column="tname" property="name" />
    </association>
</resultMap>

        一对多,即Java类的属性字段里有List这样的集合

<select id="getTeacher" resultMap="TeacherStudents">
    select s.id sid,s.name sname,t.id tid,t.name tname
    from student s,teacher t
    where s.tid=t.id and t.id=#{tid}
</select>

<resultMap id="TeacherStudents" type="Teacher">
    <result column="tid" property="id" />
    <result column="tname" property="name" />
    <!--属性是集合时,使用collection-->
    <!--javaType:指定属性的类型
        集合中的泛型信息,使用ofType获取      
    -->
    <collection property="students" ofType="Student">
        <result column="sid" property="id" />
        <result column="sname" property="name" />
        <result column="tid" property="tid" />
    </collection>
</resultMap>

        总结:

        1)属性中包含的是对象,使用association

        2)属性中包含的是集合,使用collection

        3)javaType 和 ofType的区别

                javaType:属性字段的类型

                ofType:集合中泛型的类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值