在mybatis中对于关联查询分为两种情况,一对一和一对多。
两张表连接起来时,相对应的,实体类中应该增加一个属性来维护两者之间的关联关系。
一对一
现在,要求查询学生和学生卡信息,一个学生对应一张学生卡,所以学生类中应该有一个学生卡属性,这个属性就维护了学生和学生卡之间一对一的关系。
mapper.xml
<select id="queryStudent1To1WithSid" parameterType="String" resultMap="student_card_map">
select s.*,scd.* from student s inner join studentcard scd on s.sid = scd.sid
<where>
s.sid = #{sid}
</where>
</select>
<resultMap type="entities.Student" id="student_card_map">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<!-- 一对一时,对象属性使用association映射;JavaType指定该属性的类型 -->
<association property="card" javaType="entities.StudentCard">
<id property="sid" column="sid"/>
<result property="cardinfo" column="cardinfo"/>
</association>
</resultMap>
一对一关联查询时要用到association 标签有如下常用属性
- property:对象属性的名称
- javaType:对象属性的类型
- column:所对应的外键字段名称
- select:使用另一个查询封装的结果
一对多
一个班级中有多个学生,于是需要在班级中设置一个List<Student> students
用于维系班级和学生之间的一对多关系。
mapper.xml
<!-- 一对多 -->
<select id="queryClassAndStudent" parameterType="int" resultMap="class_student_map">
select s.*,sc.* from student s inner join studentclass sc on s.classid=sc.classid
<where>
sc.classid=#{classid};
</where>
</select>
<resultMap type="entities.StudentClass" id="class_student_map">
<id property="classid" column="classid"/>
<result property="classname" column="classname"/>
<collection property="students" ofType="entities.Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
</collection>
</resultMap>
一对多关联查询时要用到collection 标签,注意:collection 中ofType属性指定集合中元素的类型