mybatis的一对多,多对一的处理

查询学生所对应的老师,学生表里有tid对应老师表的id

assiciation:对象【多对一】
collection:集合【一对多】
ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

public class Student {
    private int id;
    private String name;

    private Teacher teacher;
}

public interface StudentMapper {
    public List<Student> getStudent();
}

多对一查询:
1、查询所有学生的信息
2、根据学生的tid寻找对应的老师

按照查询嵌套处理

<mapper namespace="com.kangdamu.dao.StudentMapper">

<select id="getStudent" resultMap="StudentTeacher">
    select * from  student;
</select>
<!--学生类中有teacher这一属性,property填teacher;数据库中学生对应老师的字段为tid, column填tid;teacher为对象,需要给property赋值一个类型,所以javaType填Teacher,为了使tid查出来等于teacher,所以再加一个嵌套查询,select填写的getTeacher就是下边SQL语句的select id-->
    <resultMap id="StudentTeacher" type="Student">
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select *from teacher where id =#{id};
    </select>
</mapper>

 <select id="getStudent" resultMap="StudentTeacher2">
        select s.id as sid, s.name as sname, t.name as tname
        from student s, teacher t 
        where  s.tid =t.id
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <!-- 由于需要连表查询,需要起别名,别名需要做映射-->
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
     
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"></result>
        </association>
    </resultMap>
    
 <select id="getTeacher" resultMap="TeacherStudent">
        select s.id as sid, s.name as sname, t.name as tname,t.id as tid
        from student s, teacher t
        where  s.tid =t.id and t.id =#{tid}
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
            <result property="tid" column="tid"></result>
        </collection>
    </resultMap>
posted @ 2021-10-05 21:11  micer  阅读(167)  评论(0)    收藏  举报