10.一对多
时间:2020-07-16 23:32:42
收藏:0
阅读:70
方法一: 结果嵌套处理
子查询的由于比较繁琐就不写了 具体可以看上面的多对一 实现过程基本差不多
-
这里的关键就是配置文件的编写collection标签的使用
第一步:实体类的编写
第二步:mapper接口的编写
//获取一个老师及其下的所有学生
Teacher findTeacher(
第三步: 配置文件编写
-
在一对多中,采用的是collection标签 ofType指定相应的泛型类型
<resultMap id="TeacherMap" type="Teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" ofType="Student" >
<result property="name" column="sname"></result>
<result property="id" column="id"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
?
<select id="findTeacher" resultMap="TeacherMap">
select t.id tid,t.name tname,s.name sname,s.id
from teacher t,student s
where s.tid=t.id and t.id=#{id}
</select>
第四步:编写测试类
Test
public void findTeachers() throws Exception {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
?
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
?
Teacher teacher = mapper.findTeacher(1);
?
System.out.println(teacher);
?
sqlSession.close();
}
--------------------------------测试成功------------------------------------
原文:https://www.cnblogs.com/xuan-study/p/13325255.html
评论(0)