MyBatis之一对多关系

MyBatis之多对一和一对多

一对多理解

上次说完了多对一的关系,这次我们来说说一对多

有了上次多对一的理解,一对多理解起来并不难,一对多就是一个老师能教育多个学生。

同样的

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

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

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

           <select id="getTeacher2" resultMap="TeacherStudent2">
               select * from  mybatis.teacher  where id=#{id};
           </select>
        <!--下面的ofType指的是泛型中的类型
        1. JavaType  用来指定实体类中属性的类型
        2. ofType  用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!
        column="id" 这里的id是查询老师表中id  mybatis能够通过这个自动匹配到下面查询学生表中的id
        -->
           <resultMap id="TeacherStudent2" type="Teacher">
               <collection property="students" javaType="ArrayList"
                           ofType="Student" select="StudentByTeacherId" column="id"/>
           </resultMap>
           <select id="StudentByTeacherId" resultType="Student">
               select *from mybatis.student where tid=#{id};
           </select>
        
        • 如上可见,子查询的sql语句简单,但是映射代码逻辑增加
    • 联表查询多对一关系是最常用的,也是我最喜欢的,和子查询不同的是,sql语句复杂,但是映射关系逻辑简单,思路清晰

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

        • <mapper namespace="com.wcz.dao.StudentMapper">
          <select id="getTeacher" resultMap="TeacherStudent">
              select s.id sid,s.name sname,s.tid,t.id tid,t.name tname,t.pwd from student s,teacher t where s.tid = t.id and t.id=#{id};
          <!-- javaType  &  ofType
          1. ofType  用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!   
          -->
          </select>
              <resultMap id="TeacherStudent" type="Teacher">
                  <result property="id" column="tid"/>
                  <result property="name" column="tname"/>
                  <result property="pwd" column="pwd"/>
                  <collection property="students" ofType="Student">
                      <result property="id" column="sid"/>
                      <result property="name" column="sname"/>
                      <result property="tid" column="tid"/>
                  </collection>
              </resultMap>
          
          • 熟练这两种方式

总结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. 在子查询中需要用到javaType 和ofType,但是在联表查询中只需要用javaType即可
  4. javaType & ofType
    1. JavaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题!
  • 如果问题不好排查错误,可以使用日志 , 建议使用 Log4j
posted @ 2020-04-03 00:48  三毛是学IT掉发的  阅读(184)  评论(0编辑  收藏  举报