mybatis 一对一、一对多和多对多查询

本文详细介绍了MyBatis框架中如何实现不同类型的关联映射,包括一对一、一对多及多对一映射方式,并提供了具体的XML配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键字:association 一对一映射(一个班级只有一个班主任)

    <select id="getClass" parameterType="int" resultMap="ClassesResultMap">  
        select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id}  
    </select>  
    <resultMap type="com.lcb.user.Classes" id="ClassesResultMap">  
        <id property="id" column="c_id"/>  
        <result property="name" column="c_name"/>  
        <association property="teacher" javaType="com.lcb.user.Teacher">  
            <id property="id" column="t_id"/>  
            <result property="name" column="t_name"/>  
        </association>  
    </resultMap> 

 

 

 

关键字:collection 一对多映射(一个老师有多个学生)

    <resultMap type="Teacher" id="teacherMaps">  
        <id column="id" property="id"/>  
        <result column="name" property="name"/>  
        <result column="class_name" property="className"/>  
        <collection property="students" ofType="Student" select="getStudents" column="id">  
        </collection>  
    </resultMap>  
      
      
    <!-- 查询所有的老师级各自的所有学生 -->  
    <select id="getAllTeacher" parameterType="Teacher" resultMap="teacherMaps">  
        SELECT  
            t.id,  
            t.NAME,  
            t.class_name  
        FROM  
            teacher t  
    </select>  
      
    <select id="getStudents" parameterType="int" resultType="Student">  
        select   
            s.id,  
            s. NAME,  
            s.class_name as className  
        from student s  
        where teacher_id = #{id}  
    </select>

 

关键字:association 多对一映射(多个人属于一个国家)

             多对一相当于一对多,也可以使用collection

<select id="selectCountry" resultType="Country">  
    select cid,cname from country where cid=#{ooo}  
</select>  
  
<resultMap type="People" id="peopleMapper2">  
    <id column="pid" property="pid"/>  
    <result column="pname" property="pname"/>  
    <association property="country"   
                 javaType="Country"  
                 select="selectCountry"  
                 column="countryId" />  
</resultMap>  
  
    <select id="selectById2" resultMap="peopleMapper2">  
    select pid,pname,countryId from people where pid = #{xxx}  
</select>  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值