• Multiple students for each teacher
  • On the student side, relate, multiple students, relate to a teacher.
  • For teachers, set, one teacher has many students [one to many]



    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, 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 `, ` dar `) VALUES (1, xiao Ming, 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. Import Lombok 2. Create new entity class Teacher and Student

    @Data public class Student{ private int id; private String name; // Students need to associate with a teacher! private Teacher teacher; }
    @Data
    public class Teacher{
      private int id;
      private String name;
    
    }

    SQL > create interface teacherDAO, studentDAO

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

    4. Create the com.jialidun.dao package in the resources directory

    <! 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. Bind and register our Mapper interface or file in the core configuration file!

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

    6. Test query successfully

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