Mybatis一對多的處理
阿新 • • 發佈:2019-01-10
表的設計和Mybatis多對一相同
表的設計
利用Navicat for mysql建表,然後在檢視選單點選ER圖表(概念模型) 如下:
設計好的表ER圖表
上述表 student tid設定外來鍵參考teacher的id,所以建好表後兩者都為空要先新增teacher的資料。
多個學生對於一個老師
實體類
Teacher
public class Teacher {
private int id;
private String name;
private List<Student> students;
//省略set/get方法
}
Student
public class Student {
private int id;
private String name;
//省略set/get方法
}
編寫teacher.mapper.xml對映檔案
兩種處理方式
第一種 結果巢狀
<mapper namespace="cn.sxt.entity.teacher.mapper">
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,s.tid stid ,t.id tid,t.name tname from student s,teacher t where s.tid=t.id and tid=#{id}
</select>
<resultMap type="Teacher" id="TeacherStudent">
<id column="tid" property="id"></id>
<result column="tname" property="name"></result>
<collection property ="students" javaType="ArrayList" ofType="Student">
<id column="sid" property="id"></id>
<result column="sname" property="name"></result>
</collection>
</resultMap>
</mapper>
第二種 查詢巢狀
teacher.mapper.xml
<select id="getTeacher" resultMap="TeacherStudent">
select * from teacher where id=#{id}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<collection property="students" ofType="Student" column="id" select="cn.sxt.entity.student.mapper.getStudentById"></collection>
</resultMap>
student.mapper.xml
<mapper namespace="cn.sxt.entity.student.mapper">
<select id="getStudentById" resultType="Student">
select * from student where tid=#{id}
</select>
</mapper>
使用
public static void main(String[] args) throws IOException {
TeacherDao teacherDao=new TeacherDao();
Teacher teacher=teacherDao.getTeacher(1);
System.out.println("teacher name="+teacher.getName());
List<Student> list=teacher.getStudents();
for(Student stu:list){
System.out.println("student name="+stu.getName());
}
}