Mybatis一对多的处理

表的设计和Mybatis多对一相同


表的设计
利用Navicat for mysql建表,然后在查看菜单点击ER图表(概念模型) 如下:
Mybatis一对多的处理_第1张图片
设计好的表ER图表
Mybatis一对多的处理_第2张图片
上述表 student tid设置外键参考teacher的id,所以建好表后两者都为空要先添加teacher的数据。
Mybatis一对多的处理_第3张图片
Mybatis一对多的处理_第4张图片


多个学生对于一个老师
实体类
Teacher

public class Teacher {
    private int id;
    private String name;
    private List  students;
    //省略set/get方法
}

Student

public class Student {
    private int id;
    private String name;
    //省略set/get方法
}

编写teacher.mapper.xml映射文件

两种处理方式
第一种 结果嵌套

"cn.sxt.entity.teacher.mapper">
    
    "Teacher"  id="TeacherStudent">
        <id column="tid"  property="id">id>
        <result column="tname" property="name">result>
        property="students"  javaType="ArrayList"   ofType="Student">
            <id column="sid"  property="id">id>
            <result column="sname"  property="name">result>
        
    

第二种 查询嵌套
teacher.mapper.xml

<select id="getTeacher"  resultMap="TeacherStudent">
        select * from teacher where id=#{id}
    select>
    "TeacherStudent"  type="Teacher">
        property="students"  ofType="Student"  column="id"  select="cn.sxt.entity.student.mapper.getStudentById">
    

student.mapper.xml

namespace="cn.sxt.entity.student.mapper">
    <select id="getStudentById"    resultType="Student">
        select * from  student where tid=#{id}
    select>

使用

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  list=teacher.getStudents();
        for(Student stu:list){
            System.out.println("student name="+stu.getName());
        }
    }

你可能感兴趣的:(Mybatis)