Mybatis中的一对多的处理

如何实现SQL中的一对多的处理方式(这里是由一个老师去查询多个学生)的思路分析

    1. 第一步是先考虑是一对多 还是多对一,是先去考虑查询谁
    2. 如果是一对多,就需要在“一”的那个实体类中加一个返回“多”的那个属性生成set,gett方法
    3. 第二步就是开始写mapper的xml映射文件的SQL语句,先考虑那个实体类去主动查询另一个实体类
    4. 最终就是为了得到Student对象,所以需要先得到Teacher对象,然后在Teacher的返回集写的是student的Map集合
    5. 然后定义Map集合,然后在关联collection集合,再把整个mapper映射的xml文件路径给配置到Mybatis的全局配置文件中
    6. 最后再创建一个TeacherDao的的类创建一个得到Teacher的方法
    7. 然后测试类

mapper映射SQL的xml文件

    <!--这里是一对多查询的mapper的xml文件-->
    <select id="getTeacher" resultMap="TeacherStudent">
        SELECT s.id sid , s.name sname ,s.tid stid , t.id tid, t.name tname
                  FROM student s ,teacher t  WHERE  s.tid=t.id AND t.id=#{id}
    </select>
    <!--这里就开始写结果集部分-->
    <resultMap id="TeacherStudent" type="Teacher">
        <!--这个id的column是你要映射到SQL语句中的,这个property是你从真实的beans实体类的属性中的id-->
        <id column="tid" property="id"/>
        <result column="tname" property="name"/>
        <!--因为这个地方的是一对多,要关联到的是一个集合所以使用collection-->
        <collection property="students" ofType="Student">
            <id column="sid" property="id"/>
            <result column="sname" property="name"/>
        </collection>
    </resultMap>

在Mybatis的全局配置文件中配置mapper的路径

 <!--这个是一对多的按查询结果来映射的,如果按正规的就应该分开来写,一个bean一个mapper对应的xml-->
        <mapper resource="beans/teacher.mapper.xml"/>

创建TeacherDao类的getTeacher实现方法

package dao;

import beans.Teacher;
import org.apache.ibatis.session.SqlSession;
import util.MybatisUtil;

import java.io.IOException;

public class TeacherDao {

    //这个是得到Teacher的实体类的方法
   public Teacher getTeacher(int id) throws IOException {
        SqlSession sqlSession = MybatisUtil.getSession();
        //这部分就是用sqlSession去得到映射,返回的是Teacher类型
        Teacher teacher = sqlSession.selectOne("TeacherMapper.getTeacher",id);
        sqlSession.close();
        return teacher;
    }
}

最后测试一对多的查询

package test;

import beans.Student;
import beans.Teacher;
import dao.TeacherDao;

import java.io.IOException;
import java.util.List;

public class TestOneToMany {

    public static void main(String[] args) throws IOException {
        TeacherDao teacherDao = new TeacherDao();
        Teacher teacher = teacherDao.getTeacher(1);
        System.out.println("老师的姓名==="+ teacher.getName());
        List<Student> list = teacher.getStudents();
        for (Student student : list) {
            System.out.println("学生的姓名是>>>>"+student.getName());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36520235/article/details/79677898