2021.3.31 多对一 一对多处理
1. 测试环境搭建
多个学生一个老师;
alter table student ADD CONSTRAINT fk_tid foreign key (tid) references teacher(id)
1. 测试环境搭建
2.导入lombok
3.新建实体类Teacher,Student
4.建立Mapper接口
5.建立Mapper.xml文件
6.在核心配置文件中绑定注册我们的Mapper接口或者文件 【方式很多,随心选】
7.测试查询是否能够成功
多对一
2. 按照查询嵌套处理
studentMapper.xml文件中增加配置文件
<!-- 思路:-->
<!-- 1. 查询所有的学生信息-->
<!-- 2. 根据查询出来的学生的tid寻找特定的老师 (子查询)-->
<resultMap id="stutea2" type="Student">
<result column="id" property="id"></result>
<result property="name" column="name"></result>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
</resultMap>
<select id="getStudent4" resultMap="stutea2">
select * from student
</select>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
3.按照结果嵌套处理
<!--按照结果进行查询-->
<select id="getStudent3" resultMap="stutea">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid=t.id;
</select>
<!--结果封装,将查询出来的列封装到对象属性中-->
<resultMap id="stutea" type="Student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>
一对多
<select id="getTeacher" resultMap="STeacher">
select s.id sid,s.name sname,t.name tname,t.id tid
from teacher t,student s
where s.tid =t.id and t.id=#{tid}
</select>
<!--按结果嵌套查询 推荐使用 -->
<resultMap id="STeacher" type="Teacher">
<result column="tid" property="id"></result>
<result column="tname" property="name"></result>
<!-- 复杂的属性 我们需要单独处理 对象 association 集合collection
Java type 指定的属性类型
集合中的泛型类型 要用 oftype获取-->
<collection property="students" ofType="Student">
<result property="sid" column="id"></result>
<result property="sname" column="name"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
<!--按查询嵌套查询-->
<resultMap id="STeacher2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id">
</collection>
</resultMap>
<select id="getTeacher2" resultMap="STeacher2">
select * from teacher where id=#{tid}
</select>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{tid}
</select>

浙公网安备 33010602011771号