//学生po public class Student { //学生id 主键 private Long id; //学生姓名 private String name;
//getter and setter ... }
//老师po public class Teacher { //老师id 主键 private Long id; //老师姓名 private String name;
//getter and setter ...
}
//老师 vo public class TeacherVO extends Teacher { //学生list 因为 教师:学生 = 1 : n private List<Student> students;
// getter and setter ...
}
//关系表po
public class Relation { /* 主键 */ private Long id; /* 学生id */ private Long sid; /* 教师id */ private Long tid; // getter and setter ... }
通过关系表,连接学生表和教师表,根据id获取各自的姓名,基本业务:查询所有老师下的所有学生
手绘的...凑合看吧 哈哈,因为一个老师下有多个学生,所以在老师的实习类里声明一个学生list属性,就像上述代码一样,建立一个Vo去继承老师的实体类,下面的mapper代码是重点:
//关系表 Mapper接口
public interface RelationMapper { @Select("select id,name from TEACHER") @Results({@Result(property = "id",column = "id"), @Result(property = "name",column = "name"), @Result(property = "students",javaType = List.class,column ="id", many = @Many(select = "com.example.mapper.RelationMapper.findStudents"))}) List<TeacherVo> findTeacherAndStudents(); @Select("select s.name from RELATION r,STUDENT s where s.id = r.sid and r.tid = #{tid}") List<Student> findStudents(Long tid); }
@Select("select id,name from TEACHER") 中的id 通过 @Result(property = "students",javaType = List.class,column ="id",传到 many = @Many(select = "com.example.mapper.RelationMapper.findStudents"))})
在 List<Student> findStudents(Long tid) 中接到传递过来的id 并赋值给sql语句中 #{tid}
这样就完成了,老师学生通过关系表完成1对多。
在对应的实现类中,实现findTeacherAndStudents()方法即可,控制层同理~