多对一,一对多

一对一:
一、子查询

<select id="getStudent" resultMap="StudentMap">
        select * from mybatis.student
    </select>
    <resultMap id="StudentMap" type="Student">
        <!--复杂的属性要单独处理
        如果是对象用association
        集合使用collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
    </resultMap>
    <select id="getTeacherById" resultType="Teacher">
        select * from mybatis.teacher where id=#{dsd}
    </select>

teacher属性通过association里面又关联一个select来查询,并将student表查询出来的tid传入作为查询条件id,可以看成如下sql语句:
select * from teacher where id in (select tid from student)

二、连表查询

 <select id="getStudent2" resultMap="StudentMap2">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from mybatis.student s ,mybatis.teacher t
        where s.tid=t.id
    </select>
    <resultMap id="StudentMap2" type="Student">
        <result column="sid" property="id"/>
        <result column="sname" property="name"/>
        <association property="teacher" column="tname" javaType="Teacher">
            <result column="tname" property="name"/>
            <result column="tid" property="id"/>
        </association>

    </resultMap>

直接用一条sql语句连表查询将所要的内容全查出来,然后再用resultMap进行映射

一对多
1.连表查询

<select id="getTeacher" resultMap="TeacherMap">
        select t.id tid ,t.name tname ,s.id sid,s.name sname
        from mybatis.teacher t,mybatis.student s
        where t.id=#{tid};
    </select>
    <resultMap id="TeacherMap" type="Teacher">
        <result column="tid" property="id"/>
        <result column="tname" property="name"/>
<!--        集合用collection
            List集合中的泛型信息,用ofType-->
        <collection property="students" ofType="Student">
            <result property="name" column="sname"/>
            <result property="id" column="sid"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

注意要用collection

2.子查询

   <select id="getTeacher2" resultMap="TeacherMap2">
        select * from mybatis.teacher where id=#{tid}
    </select>
    <resultMap id="TeacherMap2" type="Teacher">
        <collection property="students"  javaType="ArrayList" ofType="Student" select="Student" column="id">
        </collection>
    </resultMap>
    <select id="Student" resultType="Student">
        select * from mybatis.student where tid=#{ ddd}
    </select>
</mapper>

注意javaType ofType

javaType:用来指定实体类中属性的类型
ofType:用来映射到List或集合中的pojo类型,泛型的约束类型

associate用来一对一和多对一,collection用来一对多

一对一,一对多,多对一:
一个用户有一个角色,多个用户可以是相同的角色,一个角色可以有多个用户

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值