关联映射之一对一

数据准备

  1. create table teacher(
  2. t_id int primary key auto_increment,
  3. t_name varchar(20)
  4. );
  5. insert into teacher(t_name) values('ZhangSan');

对应的model

  1. @Data
  2. public class Classes {
  3. private Integer id;
  4. private String name;
  5. private Teacher teacher;
  6. }

班级

  1. create table classes(
  2. c_id int primary key auto_increment,
  3. c_name varchar(20),
  4. t_id int
  5. );
  6. insert into classes(c_name,t_id) values('Class One',1);

对应的model

  1. @Data
  2. public class Teacher {
  3. private Integer id;
  4. private String name;
  5. }

mapper.xml 文件,使用了 元素映射一对一的关联关系。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.chinaunicom.kg.mapper.ClassesMapper">
  4. <select id="selectClassById" parameterType="int" resultMap="resultClassMap">
  5. SELECT c.c_id,
  6. c.c_name,
  7. t.t_id,
  8. t.t_name
  9. FROM classes c
  10. LEFT JOIN teacher t ON c.t_id = t.t_id
  11. WHERE c.c_id = #{id}
  12. </select>
  13. <!-- resultMap: 映射实体类和字段之间的一一对应的关系 -->
  14. <resultMap id="resultClassMap" type="com.chinaunicom.kg.domain.entity.Classes">
  15. <id property="id" column="c_id"/>
  16. <result property="name" column="c_name"/>
  17. <!-- 一对一关联映射:association -->
  18. <association property="teacher" javaType="com.chinaunicom.kg.domain.entity.Teacher">
  19. <id property="id" column="t_id"/>
  20. <result property="name" column="t_name"/>
  21. </association>
  22. </resultMap>
  23. </mapper>

关联映射之一对多

学生表

  1. create table student(
  2. s_id int primary key auto_increment,
  3. s_name varchar(20),
  4. c_id int
  5. );
  6. insert into student(s_name,c_id) values('s1',1);
  7. insert into student(s_name,c_id) values('s2',1);
  8. insert into student(s_name,c_id) values('s3',1);

对应的实体student

  1. @Data
  2. public class Student {
  3. private Integer id;
  4. private String name;
  5. }

对应的classes修改成

  1. @Data
  2. public class Classes {
  3. private Integer id;
  4. private String name;
  5. private List<Student> students;
  6. }

对应的mapper.xml,使用了 元素映射一对多的关联关系。

  1. <!-- resultMap: 映射实体类和字段之间的一一对应的关系 -->
  2. <resultMap id="baseClassMap" type="com.chinaunicom.kg.domain.entity.Classes">
  3. <id property="id" column="c_id"/>
  4. <result property="name" column="c_name"/>
  5. <!-- 一对多关联映射:collection -->
  6. <collection property="students" ofType="com.chinaunicom.kg.domain.entity.Student">
  7. <id property="id" column="s_id"/>
  8. <result property="name" column="s_name"/>
  9. </collection>
  10. </resultMap>
  11. <select id="selectClassAndStudentsById" parameterType="int" resultMap="baseClassMap">
  12. SELECT c.c_id, c.c_name, s.s_id, s.s_name
  13. FROM classes c
  14. LEFT JOIN student s ON c.c_id = s.c_id
  15. WHERE c.c_id = #{id}
  16. </select>