1. 程式人生 > 其它 >一對多查詢方法(和上一篇結合)

一對多查詢方法(和上一篇結合)

1.準備TeacherMapper

package com.shao.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Teacher {
    private int id;
    private String name;
    //一個老師有多個學生
    private List<Student> students;
}

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.shao.dao.TeacherMapper">
    <select id="getTeacher" resultType="Teacher">
        select * from teacher
    </select>

    <select id="getTeacherById" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname, t.id 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 property="name" column="tname"/>
        <!--
            javaType : 指定型別
            ofType : 獲取集合中的型別
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

    <select id="getTeacherById2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTid" column="id"/>
    </resultMap>
    <select id="getStudentByTid" resultType="Student">
        select * from student where tid = #{tid}
    </select>
</mapper>
主要是給自己看的,所以肯定會出現很多錯誤哈哈哈哈哈