欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

mybatis 一对一、一对多和多对多查询实例代码

时间:2022-04-18 11:43:28|栏目:JAVA代码|点击:

关键字: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>  

总结

上一篇:JavaWeb实现学生信息管理系统(2)

栏    目:JAVA代码

下一篇:java Lambda表达式的使用心得

本文标题:mybatis 一对一、一对多和多对多查询实例代码

本文地址:http://www.codeinn.net/misctech/199516.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有