zoukankan      html  css  js  c++  java
  • MyBatis之多对一关系

    MyBatis之多对一和一对多

    多对一理解

    多对一理解起来就是多张表中的数据对应一个数据,比如Student表中多个学生对应Teacher表中的一位老师。(这里指的是学校里上课的老师)通俗理解就是一个老师可以教多个学生

    MyBatis中在处理多对一的sql语句方式有两种,一种是以子查询的方式,另一种是联表查询

    • 子查询sql语句简单,但是映射关系相对复杂

      • 下面是在MyBatis中StudentMapper.xml用子查询方式进行多对一查询

        <mapper namespace="com.wcz.dao.StudentMapper">   //命名空间
        <select id="getStudent" resultMap="StudentTeacher">  //结果集反射器
           select * from  mybatis.student ;
        </select>
           <resultMap id="StudentTeacher" type="Student">
               <result property="id" column="id"/>
               <result property="name" column="name"/>
               <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
           </resultMap>
           <select id="getTeacher" resultType="Teacher">
               select * from mybatis.teacher where id=#{tid};
           </select>
        
        • 如上可见,子查询的sql语句简单,但是映射代码逻辑增加
    • 联表查询多对一关系是最常用的,也是我最喜欢的,和子查询不同的是,sql语句复杂,但是映射关系逻辑简单,思路清晰

      • 下面是在MyBatis中StudentMapper.xml下配置的联表查询操作

        • <mapper namespace="com.wcz.dao.StudentMapper">   //命名空间
          <select id="getStudent2" resultMap="StudentTeacher2">
                  select  s.id sid,s.name sname,t.name tname,t.pwd  from student s,teacher t where s.tid = t.id;
              </select>
              <resultMap id="StudentTeacher2" type="Student">
                  <result property="id" column="sid"/>
                  <result property="name" column="sname"/>
                  <association property="teacher" column="tid"  javaType="Teacher">
                      <result property="name" column="tname"/>
                      <result property="pwd" column="pwd" />
                  </association>
              </resultMap>
          
          • 熟练这两种方式
  • 相关阅读:
    EMVTag系列15《选择应用响应数据》
    EMVTag系列14《支付环境响应数据》
    EMVTag系列13《脱机PIN》
    EMVTag系列9《卡片管理数据》
    EMVTag系列7《静态签名数据》
    EMVTag系列6《IAC 发卡行行为代码》
    EMVTag系列2《磁条等效数据》
    code1169 传纸条
    关于 变量越界
    code1039 数的划分
  • 原文地址:https://www.cnblogs.com/myblogswcz/p/12623928.html
Copyright © 2011-2022 走看看