MyBatis的多表查询映射

  1. 一对多的查询

        一对多的实现,通常是在一的一方中封装一个List集合,例如

public class Clazz {
 private Integer cid;
 private String cname;
 private List<Student> stus;
 // set get⽅法
 // 构造⽅法
 // toString⽅法
}

        一对多的实现通常有两种方式:

  • collection
  • 分布查询

我们看collection实现一对多查询

首先是Mapper接口

public interface ClazzMapper {
 /**
 * 根据cid获取Clazz信息
 * @param cid
 * @return
 */
 Clazz selectByCid(Integer cid);
 /**
 * 根据班级编号查询班级信息。同时班级中所有的学⽣信息也要查询。
 * @param cid
 * @return
 */
 Clazz selectClazzAndStusByCid(Integer cid);
}

映射文件,注意是ofType,表示“集合中的类型”。

<resultMap id="clazzResultMap" type="Clazz">
 <id property="cid" column="cid"/>
 <result property="cname" column="cname"/>
 <collection property="stus" ofType="Student">
 <id property="sid" column="sid"/>
 <result property="sname" column="sname"/>
 </collection>
</resultMap>
<select id="selectClazzAndStusByCid" resultMap="clazzResultMap">
 select * from t_clazz c join t_student s on c.cid = s.cid where c.cid =
#{cid}
</select>

然后再来看分步查询

与collection不同的是xml映射文件,修改如下

<resultMap id="clazzResultMap" type="Clazz">
 <id property="cid" column="cid"/>
 <result property="cname" column="cname"/>
 <!--主要看这⾥-->
 <collection property="stus"
 select="com.powernode.mybatis.mapper.StudentMapper.selectByC
id"
 column="cid"/>
</resultMap>
<!--sql语句也变化了-->
<select id="selectClazzAndStusByCid" resultMap="clazzResultMap">
 select * from t_clazz c where c.cid = #{cid}
</select>

2、多对一查询

使用的关键词是association

//多对一时,使用的标签是association 
<resultMap id="accountMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"/>
        <association column="uid" property="user" javaType="user" select="dao.IUserDao.findById">
<!--            <id property="id" column="id"></id>-->
<!--            <result property="name" column="name"></result>-->
        </association>
    </resultMap>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值