1. 程式人生 > 實用技巧 >10.一對多

10.一對多

方法一: 結果巢狀處理

子查詢的由於比較繁瑣就不寫了 具體可以看上面的多對一 實現過程基本差不多

  • 這裡的關鍵就是配置檔案的編寫collection標籤的使用

第一步:實體類的編寫

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
private Integer id;
private String name;
private Integer tid;

}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher implements Serializable {

private Integer id;
private String name;
private List<Student> students;
}

第二步:mapper介面的編寫

//獲取一個老師及其下的所有學生
Teacher findTeacher(@Param("id") Integer id )throws Exception;

第三步: 配置檔案編寫

  • 在一對多中,採用的是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();
}

--------------------------------測試成功------------------------------------