1. 创建学生-专业表
以学生关联专业为例:创建专业表和学生表,并且在学生表中为专业id列添加外键,这样就将学生和专业表关联起来了
-- 专业表
CREATE TABLE major(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(10)
)
-- 学生表
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
num INT ,
NAME VARCHAR(10),
gender CHAR(1),
majorid INT ,
CONSTRAINT fk_student_major_majorid FOREIGN KEY(majorid) REFERENCES major(id)
)
2. 创建实体类
这里涉及类的关联,由于学生类存在多对一的关系(不同学生专业相同),专业类存在一对多的关系(一个专业对应多个学生),所以在创建类时需要将学生类和专业类进行属性关联
专业类:
学生类:
3. 进行关联查询
▐ 多对一关系查询
例如通过学生id查询到学生的专业信息
Mapper接口:
Student findStudentById(int id);
XML映射文件执行sql:
<resultMap id="studentMap" type="Student">
<id column="id" property="id"></id>
<result column="num" property="num"></result>
<result column="name" property="name"></result>
<result column="gender" property="gender"></result>
<association property="major" javaType="Major">
<result column="mname" property="name"></result>
</association>
</resultMap>
<select id="findStudentById" resultMap="studentMap">
select
s.id,s.num,,s.gender, mname
from student s inner join major m on s.majorid = m.id where s.id=#{id}
</select>
▐ resultMap属性解读
• resutlMap 的 id 属性是 resutlMap 的唯一标识,本例中定义为 "studentMap"
• resutlMap 的 type 属性是映射的 POJO 类型
• id 标签映射主键,result 标签映射非主键
• property 设置对象属性名称,column 映射查询结果的列名称
关联查询方式2:嵌套查询
除了上述的关联查询方式之外,还可以进行嵌套查询:
XML映射文件执行sql:
<resultMap id="studentMap" type="Student">
<id column="id" property="id"></id>
<result column="num" property="num"></result>
<result column="name" property="name"></result>
<result column="gender" property="gender"></result>
<association property="major" javaType="Major" select="findMajorById" column="majorid"></association>
</resultMap>
<select id="findStudentById" resultMap="studentMap">
select
id,num,name,gender,majorid
from student where id=#{id}
</select>
<select id="findMajorById" resultType="Major">
select name from major where id=#{majorid}
</select>
▐ 一对多关系查询
例如通过专业id查询到该专业下的学生信息
Mapper接口:
Major findMajorById(int id);
XML映射文件执行sql:
<resultMap id="majorMap" type="Major">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<collection property="students" javaType="list" ofType="Student">
<result column="num" property="num"></result>
<result column="sname" property="name"></result>
</collection>
</resultMap>
<select id="findMajorById" parameterType="int" resultMap="majorMap">
select
m.id,,s.num, sname
from major m inner join student s on m.id = s.majorid where m.id=#{id}
</select>
关联查询方式2:嵌套查询
同样,除了上述的关联查询方式之外,还可以进行嵌套查询:
Mapper接口:
List<Major> findMajors();
XML映射文件执行sql:
<resultMap id="majorMap1" type="Major">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<collection property="students" javaType="list" ofType="Student" select="findStudents" column="id"></collection>
</resultMap>
<select id="findMajors" resultMap="majorMap1">
select id,name from major
</select>
<select id="findStudents" resultType="Student">
select num,name from student where majorid = #{id}
</select>
运行结果: