1. 程式人生 > 其它 >多對一查詢方法

多對一查詢方法

1.sql檔案

CREATE TABLE `teacher` (
                           `id` INT(10) NOT NULL,
                           `name` VARCHAR(30) DEFAULT NULL,
                           PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老師');

CREATE TABLE `student` (
                           `id` INT(10) NOT NULL,
                           `name` VARCHAR(30) DEFAULT NULL,
                           `tid` INT(10) DEFAULT NULL,
                           PRIMARY KEY (`id`),
                           KEY `fktid` (`tid`),
                           CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小紅', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小張', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);

2.建立相應檔案

3.在mybatis-config.xml中加入

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

4.StudentMapper.java

package com.shao.dao;

import com.shao.pojo.Student;

import java.util.List;

public interface StudentMapper {
    //查詢所有的學生資訊,以及對應的老師資訊
    List<Student> getStudentList();
    List<Student> getStudentList2();
}

5.StudentMapper.xml

<?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.StudentMapper">
    <!--方法1 子查詢-->
    <select id="getStudentList" resultMap="StudentTeacher">
        select * from student
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--
            如果屬性是一個物件使用association
            如果是集合使用collection
        -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
    </resultMap>
    <select id="getTeacherById" resultType="Teacher">
        select * from teacher where id = #{tid}
    </select>
    
    <!--方法2按照結果巢狀處理-->
    <select id="getStudentList2" resultMap="StudentTeacher2">
        select  s.id sid, s.name sname, t.name tname
        from student s, teacher t
        where s.tid = t.id
    </select>
    <resultMap id="StudentTeacher2" 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>

6.結果展示

主要是給自己看的,所以肯定會出現很多錯誤哈哈哈哈哈