Mybatis-day09-复杂查询

多对一处理

一、查询嵌套查询 

<!--
    1、查询所有的学生信息
    2、根据查询出来的学生的tid,查询对应的老师
-->
    <select id="getStudent" resultMap="StudentTeacher">
        select * from mybatis.student
    </select>

    <resultMap id="StudentTeacher" type="stu">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
<!--        复杂的部分需要单独处理 对象:association 集合:collection
-->
<!--        peoperty是实体类中的属性;tid是对应的数据库中的属性;
            javaType是查询结果的实体类;select是嵌套查询的sql语句的名称-->
        <association property="teacher" column="tid" javaType="tea" select="getTeacher"/>

    </resultMap>

    <select id="getTeacher" resultType="tea">
        select * from mybatis.teacher where id = #{id}
    </select>

二、按照查询结果查询

    <!--按照查询结构嵌套-->
    <select id="getStudent2" resultMap="StudentTea">
         select s.id sid,s.name sname,t.name tname
         from student s,teacher t
         where s.tid=t.id;
    </select>
    <resultMap id="StudentTea" type="stu">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="tea">
            <result property="id" column="id"/>
            <result property="name" column="tname"/>
        </association>
    </resultMap>

ps:实体类

@Data
@Alias("stu")
public class Student {
    int id;
    String name;
    Teacher teacher;
}
@Data
@Alias("tea")
public class Teacher {
    int id;
    String name;
}

 

一对多处理

一、dao层

    //按照老师查询学生信息
    Teacher getStudent(@Param("tid") int id);

 

二、xml

<!--    根据teacher的id获取对应老师的学生 #{tid}的{}内可随意写 规范下取传入的变量-->
    <select id="getStudent" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from teacher t,student s
        where s.tid = t.id and t.id = #{tid};
    </select>
<!--   当结果为一对多时(集合),用collection
        ofType与javaType对应  是“多”的类型
-->
    <resultMap id="TeacherStudent" type="tea">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="stu">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

 三、实体类

@Data
@Alias("tea")
public class Teacher {
    int id;
    String name;

    List<Student> students;
}
@Data
@Alias("stu")
public class Student {
    int id;
    String name;
    int tid;
}

 

posted @ 2022-01-25 20:22  nlyIDE  阅读(47)  评论(0)    收藏  举报