经过前面的学习,我们掌握了一张表的增删改查的功能,接下来我们该考虑如何连接多张数据库表,本次案例:学生(student)和 老师(teacher)两张表,查询学生信息以及该学生关联的老师,介绍了两种方法。
文章目录
student 数据库:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3a9419c4c979692c97a3ca1a3f9d2c6c.png)
teacher 数据库
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3a0eda0b5295b2c2d594c78060adec8e.png)
student实体类的定义
实验目的:查询学生信息和该学生关联的老师
步骤一:在 student的实体类接口内 定义两个方法
public interface StudentMapper {
//查找所有的学生以及对应的老师信息
List<Student> getStudent01();
List<Student> getStudent02();
}
方法一:
步骤二:配置studentMpper.xml 文件
<!--
id:接口内定义的方法,
resultMap:自定义一个名字(为了使用下面的result)
先查询学生的信息
-->
<select id="getStudent01" resultMap="StudentTeacher">
select * from student
</select>
<!--
id:刚自定义的resultMap名字,
type:该方法属于的pojo
-->
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--
association :代表对象,这里赋予对象 teacher
column:数据库的字段
javaType:teacher对象的属性类型
select:嵌套的子查询
-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher01"/>
</resultMap>
<!--
子查询:再根据id查询老师信息
-->
<select id="getTeacher01" resultType="Teacher">
select * from teacher where id = #{id}
</select>
步骤三:测试
public void TestTwo(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudent01();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
方法二:
结果嵌套处理(个人较为喜欢这个)
步骤二:配置studentMpper.xml 文件
<!--
id:接口内定义的方法,
resultMap:自定义一个名字(为了使用下面的result)
直接一步查询到位(赋予别名好调用)
-->
<select id="getStudent02" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
</select>
<!--
id:刚自定义的resultMap名字,
type:该方法属于的pojo
-->
<resultMap id="StudentTeacher2" type="student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<!--
association :代表对象,这里赋予对象 teacher
javaType:teacher对象的属性类型
然后重新定义teacher数据库的字段名字
-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
步骤三:测试
@Test
public void TestThree(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudent02();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
Sum:
这次主要介绍了两个方式实现多对一的连接查询,第一种较为麻烦,需要写多个子查询然后配置associatio的标签,第二种直接不需要配置这么多的标签,较为方便,不过具体选择看实际情况。需要注意这两个方法配置association时候还是有区别的。