都知道通过mysql可以实现多表联查,前提是两个表中有互相关联的字段。那么通过Mybatis如何实现?这里记录一下简单的二表联查功能。
两个表的字段如下:

表中的数据:
student:
teacher:

情况1: 我们想要查出所有的学生的所有字段(包括所对应的老师),如何做到呢。
例:![]()
准备:
1.准备2个实体类,分别为Student和Teacher类
Student:
@Data//lombok插件简化代码
public class Student {
private int id;
private String name;
//学生关联老师
private Teacher teacher;
}
Teacher:
@Data
public class Teacher {
private int id;
private String name;
}
2.写一个student类的接口,定义查询方法。
public interface StudentMapper {
//查询所有学生的信息
List<Student> getStudent();
}
3.编写StudentMapper.xml中的相关代码
<select id="getStudent" resultMap="studentTeacher">
select s.id sid,s.name sname,t.id teid,t.name tname
from student s,teacher t
<where>
s.tid=t.id
</where>
</select>
<resultMap id="studentTeacher" type="student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
<association property="Teacher" column="teacher">
<result column="teid" property="id"></result>
<result column="tname" property="name"></result>
</association>
</resultMap>
select标签内写上sql语句,由于是多表查询,可以采用起别名的方式简化。注意:采用resultMap来接收返回值,因为Student类里面含有Teacher属性,不是基本类型。
resultMap内,基本数据类型的属性用result column propert来接收。column为实体类中的属性名(起了别名),property则是将要传入的值。非基本数据类型:Teacher类,由于这里是多个学生对应一个老师(Teacher),所以采用association(单个对象)的标签进行接收。同样,column为属性名,property内是对应的属性类型。association中的result标签的内容则与上面一致。
4.测试代码(略)。
最终结果:

情况2:查询老师名下对应的学生
例如(没截完):![]()
准备:
1.Teacher实体类中加上学生属性:
@Data
public class Teacher {
private int id;
private String name;
//一个老师关联多个学生
private List<Student> students;
}
2.TeacherMapper接口写方法
public interface TeacherMapper {
//获取指定老师的信息和学生信息
Teacher getTeacher(int id);
}
3.编写TeacherMapper.xml中的代码
<select id="getTeacher" resultMap="teacherStudent">
select t.id teid,t.name tname,s.id sid,s.name sname,s.tid
from teacher t,student s
<where>
t.id=s.tid and t.id=#{id};
</where>
</select>
<resultMap id="teacherStudent" type="teacher">
<result column="teid" property="id"></result>
<result column="tname" property="name"></result>
<collection property="students" ofType="student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
<result column="tid" property="tid"></result>
</collection>
</resultMap>
主要说明的是resultMap中的collection(集合)标签,其余的标签用法和上面一样。
这里Teacher类中的Student属性内有多个对象(老师对应多个学生),所以使用collection标签。property为属性名,而oftype则是属性的类型(student).里面的result标签用法和上面相同。
最后
以上就是舒适香菇最近收集整理的关于Mybatis实现简单的多表联查的全部内容,更多相关Mybatis实现简单内容请搜索靠谱客的其他文章。
的使用" class="embed-responsive-item">
发表评论 取消回复