实现关联表查询

一、 一对一关联(一个班级对应一个老师)

1. 按照结果嵌套查询:使用嵌套结果映射来处理重复的联合结果的子集封装联表查询的数据(去除重复的数据)

<select id="getClass" parameterType="int" resultMap="ClassResultMap">
select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
</select>

<resultMap type="Classess" id="ClassResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
</resultMap>

result嵌套result

2. 嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型

<select id="getClass2" parameterType="int" resultMap="getClass2Map">
select * from class where c_id=#{id}
</select>

<select id="getTeacher" parameterType="int" resultType="Teacher">
select t_id id,t_name name from teacher where t_id=#{id}
</select>

<resultMap type="Classess" id="getClass2Map" >
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" select="getTeacher">
</association>
</resultMap>

对象用association,集合用collection
在这里插入图片描述

二、 一对多关联(一个班级对应多个学生)

<select id="getClass" parameterType="int" resultMap="ClassResultMap">
select * from class c,teacher t,student s where c.teacher_id=t.t_id and s.class_id=c.c_id and c.c_id=#{id}
</select>

<resultMap type="Classess" id="ClassResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher"><!-- 关联 -->
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>

<collection property="students" ofType="Student"><!-- 一对多 -->
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
</collection>
</resultMap>

对象用association,集合用collection
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值