级联查询的两个标签
在级联查询的时候我们常会见到两个标签
association和collection
分别是处理哪种关系的呢?
association:处理一对一、多对一
collection:处理一对多
- 一对一:一个人对应一个身份证号码
- 一对多:一个班级对应多个学生
- 多对一:多个员工对应一个公司
一对一
xml
<select id="findNameById" resultType="java.lang.String">
SELECT username from t_account where id = #{id}
</select>
一对多
xml
<select id="findById" parameterType="long" resultType="com.a.entity.Student">
select s.id ,
s.name ,
cl.id as cid,
cl.name as cname
FROM
student s, classes cl
WHERE
s.id = #{id}
and s.cid = cl.id
</select>
- 通过学生id查班级,用到了association标签
<resultMap id="calssesMap" type="com.a.entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.a.entity.Classes">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
</association>
</resultMap>
- 通过班级id查学生,用到了collection标签
<resultMap id="calssesMap" type="com.a.entity.Classes">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<collection property="students" ofType="com.a.entity.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
</collection>
</resultMap>