Git007

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

【MyBatis学习】02、多对一查询

1.引入lombok

2.创建pojo (Student、Teacher)

import lombok.Data;

@Data
public class Teacher {
    private int id;
    private String name;

}
@Data
public class Student {
    private int id;
    private String name;

    private Teacher teacher;
}

3.编写StudentMapper Dao接口

public interface StudentMapper {
    //查询所有学生,并显示老师
    List<Student> getStudentList();
}

4.编写StudentMapper.xml文件

    association用于对象

    collection用于集合

    (1)按照结果嵌套查询

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcl.dao.StudentMapper">

    <select id="getStudentList" resultMap="StudentTeacher">
        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"/>
        </association>
    </resultMap>

</mapper>

    (2)利用子查询

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcl.dao.StudentMapper">
    
    <select id="getStudentList2" resultMap="StudentTeacher2">
        select * from student;
    </select>

    <resultMap id="StudentTeacher2" type="student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacherList"/>
    </resultMap>

    <select id="getTeacherList" resultType="teacher">
        select * from teacher where id=#{id};
    </select>

</mapper>

5.在mybatis-config.xml配置文件中注册Mapper

<mappers>
        <mapper class="com.wcl.dao.StudentMapper"/>
        <mapper class="com.wcl.dao.TeacherMapper"></mapper>
    </mappers>

6.测试

posted on   cczzhh007  阅读(28)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示