Git007

导航

【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 2022-02-22 17:10  cczzhh007  阅读(34)  评论(0)    收藏  举报