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 @   micer  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示