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>
        
        • 熟练这两种方式
posted @ 2020-04-02 23:48  三毛是学IT掉发的  阅读(118)  评论(0编辑  收藏  举报