数据库表结构
实体类
StudentMapper.xml
select * from student
测试
@Test
public void getStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.getStudent();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
方式二:按照结果嵌套处理
StudentMapper.xml
测试
@Test
public void getStudent02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.getStudent02();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
一对多(一个老师对应多个学生)
方式一:按照查询嵌套处理
TeacherMapper.xml
@Test
public void getTeacher02(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher01(1);
System.out.println(teacher);
sqlSession.close();
}
方式二:按照结果嵌套处理
TeacherMapper.xml
select s.id sid, s.name sname, t.name tname, t.id tid from student s ,teacher t where s.tid = t.id and t.id = #{tid}
测试
@Test
public void getTeacher(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
小结
1、关联 association【多对一】
2、集合 collection 【一对多】
3、javaType 和 ofType
*JavaType 用来指定实体类中属性的类型
*ofType用来指定映射到List或者集合中的实体类类型,泛型中的约束类型



