关于mybatis:练习mybatis多对一关系

34次阅读

共计 1794 个字符,预计需要花费 5 分钟才能阅读完成。

  • 多个学生,对应一个老师
  • 对于学生这边而言,关联,多个学生,关联一个老师【多对一】
  • 对于老师而言,汇合,一个老师有很多学生【一对多】

    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();}
    
    
    }

正文完
 0