一对多处理(比如一个老师对应多个学生)
测试环境搭建
-
导入lombok
-
实体类Teacher、Student
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private int id; private String name; private int tid; } @Data @AllArgsConstructor @NoArgsConstructor public class Teacher { private int id; private String name; //一个老师对应多个学生 List<Student> students; }
-
接口TeacherMapper、StudentMapper
-
可以通过注解或者xml文件进行测试,看环境是否搭建成
按照结果嵌套处理
-
TeacherMapper
public interface TeacherMapper { Teacher getTeacher(@Param("tid") int id); }
-
TeacherMapper.xml (记得在在核心配置中注册)
思路:
- 就直接连表查询
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.wjq.dao.TeacherMapper"> <!-- 按结果查询,连表查询--> <select id="getTeacher" resultMap="TeacherStudent"> select t.id tid, t.name tname, s.id sid, s.name sname 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"/> <!--当是collection时,用ofType表示属性的类型--> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> </collection> </resultMap> </mapper>
-
测试
public class UserMapperTest { @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(); } }
按照查询嵌套处理
-
TeacherMapper
Teacher getTeacher2(@Param("tid") int id);
-
TeacherMapper.xml (记得在在核心配置中注册)
?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.wjq.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="getStudent" column="id"/> </resultMap> <select id="getStudent" resultType="Student"> select * from student where tid = #{tid} </select> </mapper>
-
测试
@Test public void getStudentList2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> students = mapper.getStudentList2(); for (Student student : students) { System.out.println(student); } sqlSession.close(); }
小结:
- 关联-association【多对一】
- 集合-collection【一对多】
- javaType & ofType
- javaType 用来表示属性的返回值类型
- ofType用来表示映射对应的pojo中的类型,即泛型或者集合中的约束类型
上一节—>多对一处理
如有不对的地方欢迎指出,共同进步!