MyBatis多表联查

    <resultMap id="selTwo" type="com.bjsxt.pojo.Clazz">
        <id column="id" property="id"/>//这里特意申明是因为下面传值的时候会丢失掉这个数值
        <collection property="students" javaType="list" ofType="com.bjsxt.pojo.student"
                    select="com.bjsxt.mapper.StudentMapper.selById"
                    column="id"/>
    </resultMap>

    <select id="selAll2" resultMap="selTwo">
        select * from tb_class
    </select>

    <resultMap id="selOne" type="com.bjsxt.pojo.Clazz" autoMapping="true">
        <collection property="students" javaType="list" ofType="com.bjsxt.pojo.Student" autoMapping="true">
            <id column="sid" property="id"/>
            <result column="sname" property="name"/>
        </collection>
    </resultMap>
    <select id="selAll" resultMap="selOne">
        select
            c.*, s.id sid, s.name sname, s.gender, s.birthday
        from
            tb_class c
        left join
            tb_student s
        on
            c.id = s.cid
    </select>

上面是N+1查询,下面是多表联查。前者执行效率低,后者执行效率高。

这里也是查询班级,并且查询了这个班级的所有学生。使用的是Collection

<resultMap id="selTwo" type="com.bjsxt.pojo.Student">
        <association property="clazz"
                     javaType="com.bjsxt.pojo.Clazz"
                     select="com.bjsxt.mapper.Clazz2Mapper.selById"
                     column="cid">
        </association>
    </resultMap>
    <select id="selAll2" resultMap="selTwo">
        select * from tb_student
    </select>


    <resultMap id="selOne" type="com.bjsxt.pojo.Student" autoMapping="true">
        <association property="clazz" javaType="com.bjsxt.pojo.Clazz" autoMapping="true">
            <id column="cid" property="id" />
            <result column="cname" property="name" />
        </association>
    </resultMap>

    <select id="selAll" resultMap="selOne" >
          select
                s.*, c.name cname, c.room
            from
                tb_student s
            left join
                tb_class c
            on
                s.cid = c.id
    </select>

这里是查询学生顺便查询班级。使用的是associate。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值