mybatis之多表查询

一对一查询

resultType

 sql语句  SELECT b.*,us.id uId,us.userName uName FROM book b,USER us WHERE b.id=49 AND b.userId = us.id

确定查询的主表和关联表
创建pojo继承包括字段多的pojo,将剩余用到的字段添加进去,完成。
resultType设置成次pojo类

resultMap
将结果映射到字段多的表,在此表的pojo的属性添加另一个pojo,在resultMap中映射此pojo属性

 <resultMap id="BookExam" type="com.ssm.test.domain.BookExam">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="bookName" jdbcType="VARCHAR" property="bookname" />


    <!--评论关联的用户-->
    <association property="user" javaType="com.ssm.test.domain.User">
      <!--关联查询用户的唯一标识 javaType java类型-->
      <id column="uId" javaType="java.lang.Integer" property="id"></id>
          <result column="uName" javaType="" property="userName" />
    </association>
  </resultMap>

将User使用到的属性映射到BookExam中

总结:无特殊要求建议使用resultType(resultMap可以实现延迟加载)

一对多查询

resultType
在一的一方添加多的一方的List集合

resultMap

<!--书关联的评论
        collection关联的多条记录
        property:放在哪个属性中
        ofType:指定list集合的pojo属性
    -->
    <collection property="commentList" ofType="com.ssm.test.domain.Comment" >
      <!--评论的唯一标识-->
      <id column="cId" javaType="id" ></id>
      <result column="cComment" property="comment"></result>
      <result column="cTime" property="commenttime"></result>
    </collection>

将comment的list集合放在bookExam里,再用resultMap映射
注意:javaType必须加上

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值