关联查询

关于关联查询主要重点是配置好mapper

一对一

a.业务扩展类

核心:用resultType指定的类的属性包含多表查询的所有字段

b. resultMap

通过属性成员将2个类建立起联系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!-- 利用业务扩展类实现一对一 -->
<select id="qSByNWithO2O" resultType="top.eshyee.entity.StudentBussiness" parameterType="int">
select s.*,c.* from student s inner join studentcard c
on s.cardid =c.cardid
where s.stuno=#{stuNo}
</select>
<!-- 利用resultmap实现一对一 -->
<select id="qSByNWithMapO2O" resultMap="student_card_map" parameterType="int">
select s.*,c.* from student s inner join studentcard c
on s.cardid =c.cardid
where s.stuno=#{stuNo}
</select>
<resultMap type="student" id="student_card_map">
<id property="stuNo" column="stuNo"/>
<result property="stuName" column="stuName"/>
<result property="stuAge" column="stuAge"/>
<result property="graName" column="graName"/>
<result property="stuSex" column="stuSex"/>
<!-- 一一映射用association,一对多用collection -->
<association property="card" javaType="StudentCard">
<id property="cardId" column="cardId"/>
<result property="cardInfo" column="cardInfo"/>
</association>
</resultMap>

一对多(多对一)

(MyBatis:多对一,多对多的本质就是一对多的变化)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 查询1班的班级信息 和所有学生的信息 建立一对多关系 -->
<select id="qCAS" resultMap="class_student_classid" parameterType="int">
select c.*,s.* from student s
inner join studentclass c
on c.classid=s.classid
where c.classid=#{classId}
</select>
<resultMap type="top.eshyee.entity.StudentClass" id="class_student_classid">
<id property="classId" column="classId" />
<result property="className" column="className"/>
<!-- 属性类型用javatype 属性的元素类型用oftype -->
<collection property="student" ofType="top.eshyee.entity.Student">
<id property="stuNo" column="stuNo"/>
<result property="stuName" column="stuName"/>
<result property="stuAge" column="stuAge"/>
<result property="graName" column="graName"/>
<result property="stuSex" column="stuSex"/>
</collection>
</resultMap>

多对多

多对多 可由两个多对一等方法实现!