和前面一样我们现在反过来,查询指定老师下有多少个学生该如何做?

10.1 编写SQL

查询教师编号为1的教师教的所有学生

  1. select s.name sname,s.id sid,t.name tname,t.id tid
  2. from student s,teacher t
  3. where s.tid=t.id and t.id =1;

10.2 编写xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.lu.dao.TeacherMapper">
  6. <select id="getTeacher" resultMap="TeacherStudent">
  7. select s.name sname, s.id sid, t.name tname, t.id tid
  8. from student s,
  9. teacher t
  10. where s.tid = t.id
  11. and t.id = #{tid};
  12. </select>
  13. <!--查询所有老师下的学生,先查询老师-->
  14. <resultMap id="TeacherStudent" type="Teacher">
  15. <result property="id" column="tid" />
  16. <result property="name" column="tname"/>
  17. <collection property="students" ofType="Student">
  18. <result property="id" column="sid"/>
  19. <result property="name" column="sname"/>
  20. <result property="tid" column="tid"/>
  21. <association property="teacher" javaType="Teacher">
  22. <result property="id" column="tid"/>
  23. <result property="name" column="tname"/>
  24. </association>
  25. </collection>
  26. </resultMap>
  27. </mapper>

这是一个简单的 多表查询的例子
需要注意的是这里的 一对多 是 用 collection 表示 oftype 表示 集合内元素类型。

10.3 测试

  1. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
  2. SqlSession sqlSession = sqlSessionFactory.openSession();
  3. sqlSession.getMapper(TeacherMapper.class).getTeacher(1).getStudents().forEach(System.out::println);
  4. sqlSession.close();
  1. Student(id=1, name=Tom, tid=1, teacher=Teacher(id=1, name=Teacher Zhang, students=[]))
  2. Student(id=2, name=Jack, tid=1, teacher=Teacher(id=1, name=Teacher Zhang, students=[]))
  3. Student(id=3, name=Alice, tid=1, teacher=Teacher(id=1, name=Teacher Zhang, students=[]))
  4. Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@22fcf7ab]