上一篇文章讲解了Mybatis如何处理一对多关系,这篇将讲述MyBatis如何处理多对一关系,如果没看上一篇文章可能不知道文章关于数据库表计以及属性的设计,请移步上一篇文章
https://blog.csdn.net/QYH7777/article/details/105538945
多对一
在多对一中,我们需要修改实体类中的一些属性
数据库中student对teacher是多对一,而teacher对student是一对多
所以我们Student 新添一个tid,Teacher类中添加一个Student的属性
package com.qyh.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int tid;
}
package com.qyh.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//老师包含多个学生
private List<Student> students;
}
我们仍然采用子查询和结果嵌套两种方式来进行编写
下边是Mapper类和xml的代码
package com.qyh.dao;
import com.qyh.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
public interface TeacherMapper {
//查询老师
// List<Teacher> getTeacher();
//获取指定老师下的所有学生信息和老师信息
Teacher getTeacher(@Param("tid") int id);
Teacher getTeacher2(@Param("tid") int id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qyh.dao.TeacherMapper">
<!-- 按结果嵌套-->
<resultMap id="TeacherStudent" type="Teacher">
<result column="tid" property="id"/>
<result column="tname" property="name"/>
<!--老师中学生对象属于集合
复杂的属性需要单独处理 对象:association 集合:collection
javaType="" 指定属性的类型
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<result column="tid" property="tid"/>
</collection>
</resultMap>
<select id="getTeacher" resultMap="TeacherStudent ">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<!--=======================================================-->
<!--方式二
子查询
-->
<resultMap id="TeacherStudent2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id" />
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid}
</select>
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id = #{tid}
</select>
</mapper>
这里讲一下xml中使用到的ofTypehe javaType
javaType:用来指定实体类中属性的类型
ofType:用来指定映射到List或者集合中pojo的类型,简单说就是泛型中约束的类型!
多对一和一对多在理解方面大致一样,所以这里不多做赘述。
总结一下:
关联:association 多对一
集合:cllection 一对多