文章目录
项目搭建过程
参考我的博客:10. 多对一、一对多 的实验环境搭建
其中实体类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;
//一个老师拥有多个学生
private List<Student> students;
}
最终项目结构:
编写TeacherMapper接口方法
public interface TeacherMapper {
//获取老师
List<Teacher> getTeacher();
//获取指定老师下的所有学生及老师的信息
Teacher getTeacher2(@Param("tid") int id);
Teacher getTeacher3(@Param("tid") int id);
}
编写TeacherMapper.xml的sql
1. --------------这个查出来,teacher为null
<select id="getTeacher" resultType="com.pojo.Teacher">
select * from teacher
</select>
console输出结果:
2. --------------按照查询嵌套处理【不推荐】
<select id="getTeacher3" resultMap="StudentTeacher2">
select * from teacher where id=#{tid}
</select>
<resultMap id="StudentTeacher2" type="com.pojo.Teacher">
<collection property="students" javaType="ArrayList" ofType="com.pojo.Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="com.pojo.Student">
select * from student where tid=#{tid}
</select>
console输出结果:
3.--------------按照结果嵌套处理【推荐】
<select id="getTeacher2" resultMap="StudentTeacher">
SELECT s.id sid, s.name sname,t.name tname,t.id tid FROM student s, teacher t
WHERE s.tid = t.id AND tid = #{tid}
</select>
<resultMap id="StudentTeacher" type="com.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection
javaType=""指定属性的类型!
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="com.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
console输出结果: