问题引入:一个老师对应了很多个学生,如何在查询老师的同时,将老师底下的学生也查询出来,涉及两张表
思路:
SELECT s.id as sid,s.name as sname,t.name as tname,t.id as tid
FROM student s,teacher t
where s.tid =t.id
结果:
Mybatis中提供了resultMap元素下的collection子元素,来处理一对多的关联关系,collection中包含了一个特殊属性:ofType,与javaType相对应,用于指定实体类对象中集合类属性所包含的元素类型。
1、搭建环境
2、配置文件
3、提取工具类
4、创建实体类
以上步骤都在第四个Mybatis程序中有。
5、创建dao接口
public interface TeacherMapper {
Teacher getTeacher1(int id);
Teacher getTeacher2(int id);
}
public interface StudentMapper {
}
6、注册Mapper
<mappers>
<mapper class="com.dao.StudentMapper"/>
<mapper class="com.dao.TeacherMapper"/>
</mappers>
7、解决问题
①、嵌套结果查询
<!--结果嵌套-->
<select id="getTeacher1" parameterType="int"
resultMap="TeacherOfStudent1">
select s.id sid,s.name sname,t.id tid,t.name tname
from mydatabase.teacher t,mydatabase.student s
where t.id=s.tid and t.id = #{tid};
</select>
<!--id用于在主查询中使用-->
<resultMap id="TeacherOfStudent1" type="Teacher">
<!--设置主键 property为指定实体类中的属性名,
column为数据库中的属性名,注意映射关系-->
<id property="id" column="tid"/>
<result property="name" column="tname"/>
<!--collection中的property为Teacher实体类中引入的学生类的学生-->
<collection property="students" ofType="Student">
<id property="id" column="sid"/>
<result property="tid" column="tid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
<!--查询嵌套-->
<select id="getTeacher2" parameterType="int"
resultMap="TeacherOfStudent2">
select * from mydatabase.teacher where id=#{id}
</select>
<!--主查询-->
<resultMap id="TeacherOfStudent2" type="Teacher">
<!--设置主键,如果不设置,
查询结果将出现秦老师后面的id=0的情况-->
<id property="id" column="id"/>
<!--select传入次查询的bean id
column是关联查询下个sql语句的传递值,
与上面的主键id相对应,如果不写,则查询结果报错
在collection中还可以加入javaType元素,
一般javaType=ArrayList,或者是java.util.List
-->
<collection property="students" ofType="Student"
select="getStudent" column="id">
<!--设置次查询的主键-->
<id property="id" column="id"/>
</collection>
</resultMap>
<!--次查询,id用于在主查询中引入-->
<select id="getStudent" resultType="Student">
select * from mydatabase.student where tid=#{tid}
</select>
8、结果:
public class test {
@Test
public void test1(){
TeacherMapper mapper =
MybatisUtil.getSqlSessionFactory().getMapper(TeacherMapper.class);
System.out.println(mapper.getTeacher1(1));
}
@Test
public void test2(){
TeacherMapper mapper =
MybatisUtil.getSqlSessionFactory().getMapper(TeacherMapper.class);
System.out.println(mapper.getTeacher2(1));
}
}
9、可能出现的问题
- 结果中红框,的id=0,如果在嵌套的时候,未传入主键id,就会出现这个问题,已经注释在了xml中