好比:一個老師擁有多個學生!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優化
面試高頻日誌