mybatis 一对多
@Data
public class Teacher {
private int id;
private String name;
//一个老师有多个学生
private List<Student> students;
}
public interface TeacherMapper {//获取指定老师下的所有学生及老师的信息 Teacher getTeacher(@Param("tid") int id); }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rzk.mapper.TeacherMapper">
<!--按结果嵌套查询 resultMap对应下面resultMap的id-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname,t.id tid,t.name tname
from teacher t ,student s
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>
@Test
public void getStudentByTeacher(){
SqlSession sqlSessionFactory = MybatisUtils.getSqlSessionFactory();
TeacherMapper mapper = sqlSessionFactory.getMapper(TeacherMapper.class);
Teacher teacher2 = mapper.getTeacher2(1);
System.out.println(teacher2);
sqlSessionFactory.close();
}
<!--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)])-->