Mybatis一对多的处理
程序员文章站
2022-05-09 19:06:30
...
表的设计和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());
}
}
查询嵌套原理,例析:
映射文件:
这种方式里的Minister属性mid、mname是通过查询得到的,而非定义包装的。
将查询到的mid、mname再传给Country类里的ministers集合。