关联映射之一对一
数据准备
create table teacher(
t_id int primary key auto_increment,
t_name varchar(20)
);
insert into teacher(t_name) values('ZhangSan');
对应的model
@Data
public class Classes {
private Integer id;
private String name;
private Teacher teacher;
}
班级
create table classes(
c_id int primary key auto_increment,
c_name varchar(20),
t_id int
);
insert into classes(c_name,t_id) values('Class One',1);
对应的model
@Data
public class Teacher {
private Integer id;
private String name;
}
mapper.xml 文件,使用了
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chinaunicom.kg.mapper.ClassesMapper">
<select id="selectClassById" parameterType="int" resultMap="resultClassMap">
SELECT c.c_id,
c.c_name,
t.t_id,
t.t_name
FROM classes c
LEFT JOIN teacher t ON c.t_id = t.t_id
WHERE c.c_id = #{id}
</select>
<!-- resultMap: 映射实体类和字段之间的一一对应的关系 -->
<resultMap id="resultClassMap" type="com.chinaunicom.kg.domain.entity.Classes">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- 一对一关联映射:association -->
<association property="teacher" javaType="com.chinaunicom.kg.domain.entity.Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
</resultMap>
</mapper>
关联映射之一对多
学生表
create table student(
s_id int primary key auto_increment,
s_name varchar(20),
c_id int
);
insert into student(s_name,c_id) values('s1',1);
insert into student(s_name,c_id) values('s2',1);
insert into student(s_name,c_id) values('s3',1);
对应的实体student
@Data
public class Student {
private Integer id;
private String name;
}
对应的classes修改成
@Data
public class Classes {
private Integer id;
private String name;
private List<Student> students;
}
对应的mapper.xml,使用了
<!-- resultMap: 映射实体类和字段之间的一一对应的关系 -->
<resultMap id="baseClassMap" type="com.chinaunicom.kg.domain.entity.Classes">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- 一对多关联映射:collection -->
<collection property="students" ofType="com.chinaunicom.kg.domain.entity.Student">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
</collection>
</resultMap>
<select id="selectClassAndStudentsById" parameterType="int" resultMap="baseClassMap">
SELECT c.c_id, c.c_name, s.s_id, s.s_name
FROM classes c
LEFT JOIN student s ON c.c_id = s.c_id
WHERE c.c_id = #{id}
</select>