九.一对多处理

1.   2个类,搞里头

测试样例是:查询一个老师,所拥有的学生数量

package com.why.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * @program: Mybatis_annotation
 * @description:
 * @author: @why
 * @create: 2020-08-29 10:25
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher {
    private  Integer id;
    private  String name;
    //一个老师所拥有的学生
    private List<Student> students;
}
package com.why.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @program: Mybatis_annotation
 * @description:
 * @author: @why
 * @create: 2020-08-29 10:25
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private  Integer id;
    private  String name;
    private  Integer tid;
//    //根据tid可以得到每个学生所对应的老师,也就是多对一处理
//    private  Teacher teacher;

}

2.xml搞里头       别忘了在配置文件中注册

方法一:按照查询结果处理 

 

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.why.Mapper.TeacherMapper">
    <select id="getAllMsg" resultMap="stuMsg">
select tea.id tid,tea.`name` tname, stu.id sid,stu.`name` sname,stu.tid stid from teacher tea
join student stu
on  stu.tid=tea.id;</select>

<resultMap id="stuMsg" type="teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--        对象用association 集合用  collection-->
    <!--        javaType  指定的属性类型-->
    <!--        ofType  集合的类型-->
    <collection property="students" ofType="student">

        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="stid"/>
    </collection>
</resultMap>
</mapper>

方法二:按照查询嵌套处理 不喜欢

先映射一个map
<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</select>
对映射的map进行处理
<resultMap id="TeacherStudent2" type="Teacher">
      因为teacher中有list集合 所以给javatype  oftype是list的实际类型
    <collection property="students" javaType="ArrayList" ofType="Student" 
                将第一个查询的id 给第二个查询
                select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = #{tid}
</select>

 

posted @ 2020-08-29 12:04  why666  阅读(127)  评论(0编辑  收藏  举报