Mybatis——一对多的处理
1.环境搭建,和多对一一样
实体类
package com.yl.pojo;
import lombok.Data;
package com.yl.pojo;
import lombok.Data;
import java.util.List;
按结果嵌套查询
<select id="getTeacherById" resultMap="TeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from student s,teacher t
    where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--对象使用association 集合使用collection
    javaType:指定属性的类型
    集合中的泛型信息,使用ofType
    --> 
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
按照查询嵌套(子查询)
<select id="getTeacherById" resultMap="TeacherStudent">
    select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
    select * from student where tid = #{tid}
</select>
小结
1.关联:association 多对一
2.集合:collection 一对多
3.javatype:用来指定实体类中属性的类型
4.ofType:用来指定映射到集合中的pojo类型,泛型中的约束类型
注意点
1.保证sql的可读性,尽量保证通俗易懂
2.注意属性名和字段的问题
3.如果问题不好排错,可以使用日志
面试:
- 
Mysql引擎 
- 
InnoDB底层原理 
- 
索引 
- 
索引优化 
- 
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号