上一篇博文我们讲的是Mybatis实现sql语句的多对一处理,学生对于老师来说,是一种多对一的关系,而老师对于学生来说呢,是一种一对多的关系,接下来我们就来看看相关操作。
步骤一: 构造学生,老师实体类
package com.hpf.bean;
import lombok.Data;
@Data
public class Student {
private int id;
private String stuName;
private int teaId;
}
#####################################################################
package com.hpf.bean;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String teaName;
//一个老师拥有多个学生
private List<Student> students;
}
步骤二: 编写TeacherMapper.java接口类
package com.hpf.dao;
import com.hpf.bean.Teacher;
import java.util.List;
public interface TeacherMapper {
//查询指定老师的信息及其包含的学生信息
Teacher getTeacherInfo(int id);
}
步骤三: 编写xml映射配置文件(方式一)
<?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.hpf.dao.TeacherMapper">
<!--按照结果嵌套查询-->
<select id="getTeacherInfo" resultMap="tea-stu">
select s.id sid,s.stu_name,t.id tid,t.tea_name
from student s,teacher t
where s.tea_id = t.id and t.id = #{id}
</select>
<resultMap id="tea-stu" type="Teacher">
<result property="id" column="tid"/>
<result property="teaName" column="tea_name"/>
<!--
复杂的属性,我们需要单独处理
对象用:association
集合用:collection
javaType="" 指定属性的类型
ofType 用于获取集合当中的泛型信息
-->
<collection property="students" ofType="com.hpf.bean.Student">
<result property="id" column="sid"/>
<result property="stuName" column="stu_name"/>
<result property="teaId" column="tid"/>
</collection>
</resultMap>
</mapper>
步骤三: 编写xml映射配置文件(方式二)
<!--子查询-->
<select id="getTeacherInfo2" resultMap="tea-stu2">
select * from teacher where id = #{id};
</select>
<resultMap id="tea-stu2" type="Teacher">
<result property="id" column="id"/>
<collection property="students" javaType="List" ofType="Student" select="getStudentByTeaId" column="id">
</collection>
</resultMap>
<select id="getStudentByTeaId" resultType="Student">
select * from student where tea_id = #{id}
</select>
总结:
- 多对一指的是关联关系,我们使用的是association;
- 一对多指的是集合关系,我们使用的是collection;
- javaType & ofType 区别:
javaType用来指定实体类中属性的类型
ofType用来指定映射到List或者集合当中的pojo类,也就是泛型中的约束类型!