Mybatis-学习笔记(4)1对1、1对多、多对多

1、1对1

   有2种方式对内嵌Bean设值:

    1》关联查询就一条语句。使用association关键字,直接将嵌套对象的映射表的字段赋值内嵌对象。

<association property="teacher" javaType="com.lfy.bean.Teacher">
     <id property="id" column="t_id"/>
     <result property="name" column="t_name"/>
</association>

     2》在同一个mapper中写嵌套bean的映射查询,或者嵌套bean的查询在独立的mapper中。还是使用association关键字。

<!-- getTeacher为同mapper的一个查询。对内嵌teacher属性进行关联查询 -->
<
resultMap type="com.lfy.bean.Classes" id="ClassesResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher" javaType="com.lfy.bean.Teacher"/> </resultMap>
<!-- getTeacher为其他mapper的一个查询。对内嵌teacher属性进行关联查询 -->
<resultMap type="com.lfy.bean.Classes" id="ClassesResultMap2">
    <id property="id" column="c_id"/>
    <result property="name" column="c_name"/>
    <association property="teacher" column="teacher_id" select="com.lfy.mapper.teacherMapper.getTeacher" javaType="com.lfy.bean.Teacher"/>
</resultMap>

    总结:关键字association。

2、1对多

  外键一般放置在多方,如学生与班级的关系,多个学生对应一个班级,是多对一的关系,外键应该放在学生表中,即学生表参照了班级表。

  但我们现在的需求是,查询出某班级,并查询出班级的所有学生,班级与学生的关系是一对多的关系。

    <!-- 根据id查询班级信息,返回resultMap -->
    <select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
        SELECT * FROM tb_clazz  WHERE id = #{id}
    </select>
      
       <!-- 映射Clazz对象的resultMap -->
    <resultMap type="com.lfy.bean.Clazz" id="clazzResultMap">
        <id property="id" column="id"/>
        <result property="code" column="code"/>
        <result property="name" column="name"/>
        <!-- 一对多关联映射:collection fetchType="lazy"表示懒加载  -->
        <collection property="students" javaType="ArrayList"
            column="id" ofType="com.lfy.bean.Student"
            select="com.lfy.mapping.StudentMapper.selectStudentByClazzId"
            fetchType="lazy">
          <id property="id" column="id"/>
          <result property="name" column="name"/>
          <result property="sex" column="sex"/>
          <result property="age" column="age"/>
        </collection>
     </resultMap>

  fetchType属性:有两个取值eager和lazy,eager表示立即加载,是默认的加载形式。在查询Clazz对象的时候,会立即执行关联的selectStudentByClazzId中定义的SQL语句去查询班级的所有学生;lazy表示懒加载,其不会立即发送SQL语句去查询班级的所有学生,而是等到需要使用到班级的students属性时,才会发送SQL语句去查询班级的所有学生信息。

  fetch机制更多的是为了性能考虑,如果查询班级时确定会访问班级的所有学生,则该属性应该设置为eager;如果查询班级时只是查询班级信息,有可能不会访问班级的所有学生,则该属性应该设置为lazy。一般情况下,一对多所关联的集合对象,都应该被设置成lazy。

  使用懒加载,还需要在Mybatis配置文件中增加如下配置:

  

   总结:关键字collection。

3、多对多

  数据库中的多对多关系,推荐使用中间表来维护关系,中间表中的订单id作为外键参照订单表的id,商品id作为外键参照商品表的id。

  主要是对前面两种的总和应用。

原文地址:https://www.cnblogs.com/ZeroMZ/p/11415836.html