- 点击此处查看多对一处理(有基本的环境搭建)
- 对于老师而言,一个老师,有很多学生【一对多】(集合)
1、按照结果嵌套处理
-
接口TeacherMapper
public interface TeacherMapper { //获取指定老师下的所有学生及老师信息 Teacher getTeacher(@Param("tid") int id); }
-
TeacherMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ping.dao.TeacherMapper"> <!--按照结果嵌套查询--> <select id="getTeacher" resultMap="TeacherStudent"> 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}; </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <!--复杂的属性,需要单独处理, 对象:association, 集合:collection javaType="" 指定属性的类型 集合中的泛型信息,使用ofType获取 --> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap> </mapper>
-
测试类
public class Mytest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = mapper.getTeacher(1); System.out.println(teacher); /* Teacher(id=1, name=王老师, students=[Student(id=1, name=小明, tid=1), Student(id=2, name=小红, tid=1), Student(id=3, name=小张, tid=1), Student(id=4, name=小李, tid=1), Student(id=5, name=小王, tid=1)]) */ sqlSession.close(); } }
-
测试结果
2、按照查询嵌套处理
-
接口TeacherMapper
public interface TeacherMapper { //获取指定老师下的所有学生及老师信息 Teacher getTeacher2(@Param("tid") int id); }
-
TeacherMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ping.dao.TeacherMapper"> <!--按照查询嵌套处理--> <select id="getTeacher2" resultMap="TeacherStudent2"> select * from teacher where id = #{tid}; </select> <resultMap id="TeacherStudent2" type="Teacher"> <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/> </resultMap> <select id="getStudentByTeacherId" resultType="Student"> select * from student where tid = #{tid} </select> </mapper>
-
测试类
public class Mytest { @Test public void test2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class); Teacher teacher = mapper.getTeacher2(1); System.out.println(teacher); /* Teacher(id=1, name=王老师, students=[Student(id=1, name=小明, tid=1), Student(id=2, name=小红, tid=1), Student(id=3, name=小张, tid=1), Student(id=4, name=小李, tid=1), Student(id=5, name=小王, tid=1)]) */ sqlSession.close(); } }
-
测试结果