image.png

  • 多个学生,对应一个老师
  • 对于学生这边而言,关联, 多个学生,关联一个老师【多对一】
  • 对于老师而言,集合,一个老师有很多学生【一对多】
    image.png
    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=utf8INSERT 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);

    测试环境搭建
    1.导入lombok
    2.新建实体类Teacher,Student

    @Data
    public class Student{
      private int id;
      private String name;
      //学生需要关联一个老师!
      private Teacher teacher;
    }
    @Data
    public class Teacher{
      private int id;
      private String name;
    
    }

    3.建立Dao接口TeacherDao,StudentDao

    public interface TeacherDao{
      @Select("select * from teacher where id=#{tid}")
      Teacher getTeacher(@Param("tid") int id);
    }
    public interface StudentDao{
    
    
    }

    4.建立Mapper.xml文件
    在resources目录创建com.jialidun.dao包

    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.jialidun.dao.TeacherDao">
      
    </mapper>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.jialidun.dao.StudentDao">
      
    </mapper>

    5.在核心配置文件中绑定注册我们的Mapper接口或者文件!

    <mappers>
      <mapper resource="com/jialidun/dao/*.xml"/>
      <mapper class="com.jialidun.dao.*"/>
    </mappers>

    6.测试查询成功

    public class TestDemo{
      @Test
      public void test01(){
          SqlSession sqlSession = MybatisUtils.getSqlSession();
          TeacherDap mapper = sqlSession.getBean(TeacherDao.class);
          Teacher teacher = mapper.getTeacher(1);
          System.out.println(teacher);
          sqlSession.close();
      }
    
    
    }

RYGAR
1 声望0 粉丝

引用和评论

0 条评论