mapper 层
a)在 StudentMapper.xml 中定义多表连接查询 SQL 语句, 一次性查到需要的所有数据, 包括对应班级的信息.
b)通过<resultMap>定义映射关系, 并通过<association>指定对象属性的映射关系. 可以把<association>看成一个<resultMap>使用. javaType 属性表示当前对象, 可以写全限定路径或别名.
<?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.bjsxt.mapper.StudentMapper">
<resultMap type="Student" id="smap">
<id property="stid" column="sid"/>
<result property="stname" column="name"/>
<result property="stage" column="age"/>
<result property="stsex" column="sex"/>
<result property="stcid" column="c_id"/>
<!-- 用于关联一个对象 -->
<association property="clazz" javaType="clazz">
<id property="id" column="cid"/>
<result property="name" column="cname"/>
<result property="room" column="croom"/>
</association>
</resultMap>
<select id="selAll" resultMap="smap">
select s.sid,s.name,s.age,s.sex,s.c_id,c.cid,c.cname,c.croom
from t_stu s
left join t_class c
on s.c_id=c.cid
</select>
</mapper>
Test测试类:
package com.bjsxt.test;
import java.util.List;
import com.bjsxt.pojo.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.Impl.StudentServiceImpl;
public class TestSel {
public static void main(String[] args) {
StudentService ss=new StudentServiceImpl();
List<Student> list = ss.selAll();
for (Student student : list) {
System.out.println(student);
}
}
}
其余的配置文件参考:Mybatis_多表关联查询_resultMap_集合对象_N+1方式实现(不需要ClazzMapper)
运行截图: