问题
mybatis 如何实现连表查询
详细问题
笔者有三个表:学生表,选课表,课程表
学生表有以下字段
id为学生编号
name为学生姓名
age为学生年龄
class为学生班级
选课表有以下字段
id为选课编号
stu_id为学生编号
course_id为课程编号
课程表有以下字段
id为课程编号
credit为课程学分
要求使用mybatis查询结果为学生信息(姓名、班级等)、选课学分总和
解决方案一
1 创建结果类,只需包含查询结果所需字段
public class Student1 {
private String name;
private String _class;
private Double sum;
@Override
public String toString() {
return "Student1{" +
"name='" + name + '\'' +
", _class='" + _class + '\'' +
", sum=" + sum +
'}';
}
}
2 在xml中编写查询语句
<select id="selectStuTotalCredits" parameterType="Integer" resultMap="studentTotalCreditsResult">
SELECT s.NAME, s.class, SUM(c.credit) as sum_
FROM student s
JOIN select_course sc ON s.ID = sc.stu_id
JOIN course c ON sc.course_id = c.id
GROUP BY s.ID
LIMIT #{offset}, 5
</select>
3 在xml中定义返回结果集
<resultMap id="studentTotalCreditsResult" type="com.haut.rgzndsj.po.Student1">
<result property="name" column="name"/>
<result property="_class" column="class"/>
<result property="sum" column="sum_"/>
</resultMap>
解决方案二
1 在xml中编写查询语句
<select id="selectStuTotalCredits" parameterType="Integer" resultMap="studentTotalCreditsResultMap">
SELECT s.NAME, s.class, SUM(c.credit) as sum_
FROM student s
JOIN select_course sc ON s.ID = sc.stu_id
JOIN course c ON sc.course_id = c.id
GROUP BY s.ID
LIMIT #{offset}, 5
</select>
2 在xml中定义返回结果集
<resultMap id="studentTotalCreditsResultMap" type="com.haut.rgzndsj.po.Student">
<id property="id" column="ID"/>
<result property="name" column="NAME"/>
<result property="age" column="AGE"/>
<result property="_class" column="class"/>
<collection property="selectCourses" ofType="com.haut.rgzndsj.po.SelectCourse">
<id property="id" column="id"/>
<result property="course_id" column="course_id"/>
<result property="stu_id" column="stu_id"/>
<association property="course"
javaType="com.haut.rgzndsj.po.Course" select="selectCourseCreditById"
column="id">
</association>
</collection>
</resultMap>
原因
基于mybatis的api即可
总结
上述两种方案虽都可以实现,但各有优劣
解决方案一:
优:
(1)无需梳理清楚查询对象之间数据对应关系 ,相对简单
劣:
(1)需新建结果类
解决方案二:
优:
(1)无需新建结果类
劣:
(2)确定需查询对象之间数据对应关系(一对一,一对多,多对多),逻辑较为复杂
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈