10.一對多
阿新 • • 發佈:2020-07-16
方法一: 結果巢狀處理
子查詢的由於比較繁瑣就不寫了 具體可以看上面的多對一 實現過程基本差不多
-
這裡的關鍵就是配置檔案的編寫collection標籤的使用
第一步:實體類的編寫
第二步:mapper介面的編寫
//獲取一個老師及其下的所有學生
Teacher findTeacher(
第三步: 配置檔案編寫
-
在一對多中,採用的是collection標籤 ofType指定相應的泛型型別
<resultMap id="TeacherMap" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" ofType="Student" >
<result property="name" column="sname"></result>
<result property="id" column="id"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
<select id="findTeacher" resultMap="TeacherMap">
select t.id tid,t.name tname,s.name sname,s.id
from teacher t,student s
where s.tid=t.id and t.id=#{id}
</select>
第四步:編寫測試類
Test
public void findTeachers() throws Exception {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.findTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
--------------------------------測試成功------------------------------------