mybatis:一对多处理
1.实体类编写
@Data
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private int tid;
}
@Data
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
2.按结果嵌套处理
1.TeacherMapper接口编写方法
//获取指定老师下的所有学生及老师的信息
Teacher getTeacher(@Param("tid") int id);
2.编写接口对应的Mapper配置文件
<!--按结果嵌套查询-->
<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>
按查询嵌套查询
1.TeacherMapper接口编写方法
Teacher getTeacher2(int id);
2.编写接口对应的Mapper配置文件
<resultMap id="TeacherStudent2" type="Teacher">
<!--column是一对多的外键,写的是一的主键的列名-->
<collection property="students" javaType="Arraylist" ofType="Student"
column="id" select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid =#{id}
</select>
测试: