好比:一个老师拥有多个学生!java
对于老师而言,就是一对多的关系!面试
实体类sql
@Data public class Student { private int id; private String name; private int tid; }
@Data public class Teacher { private int id; private String name; //一个老师拥有多个学生 private List<Student> students; }
<!--按结果嵌套查询--> <select id="getTeacher" 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="getTeacher2" resultMap="TeacherStudent2"> select * from mybatis.teacher where id = #{tid} </select> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/> </resultMap> <select id="getStudentByTeacherId" resultType="Student"> select * from mybatis.student where tid = #{tid} </select>
注意点:mybatis
慢SQL 1s 1000s优化
面试高频日志