mybatis 连表查询

问题

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)确定需查询对象之间数据对应关系(一对一,一对多,多对多),逻辑较为复杂

原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞滕人生TYF

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值