1、 所谓自关联是指,自己即充当一方,又充当多方,是 1:n 或 n:1 的变型。例如,对于新
闻栏目 NewsColumn,可以充当一方,即父栏目,也可以充当多方,即子栏目。而反映到 DB
表中,只有一张表,这张表中具有一个外键,用于表示该栏目的父栏目。一级栏目没有父栏
目,所以可以将其外键值设为 0,而子栏目则具有外键值。
为了便于理解,将自关联分为两种情况来讲解。一种是当作 1:n 讲解,即当前类作为一
方,其包含多方的集合域属性。一种是当作 n:1 讲解,即当前类作为多方,其包含一方的域
<result column="name" property="name"/>
<collection property="children"
ofType="NewsLabel"
select="selectChildrenByParent"
column="id"/>
</resultMap>
<select id="selectChildrenByParent" resultMap="newsLabelMapper">
select id,
name from tb_newslabel where pid=#{xxx}
闻栏目 NewsColumn,可以充当一方,即父栏目,也可以充当多方,即子栏目。而反映到 DB
表中,只有一张表,这张表中具有一个外键,用于表示该栏目的父栏目。一级栏目没有父栏
目,所以可以将其外键值设为 0,而子栏目则具有外键值。
为了便于理解,将自关联分为两种情况来讲解。一种是当作 1:n 讲解,即当前类作为一
方,其包含多方的集合域属性。一种是当作 n:1 讲解,即当前类作为多方,其包含一方的域
属性。
2、导航栏目的自关联
(1)
<resultMap type="NewsLabel" id="newsLabelMapper" >
<id column="id" property="id"/><result column="name" property="name"/>
<collection property="children"
ofType="NewsLabel"
select="selectChildrenByParent"
column="id"/>
</resultMap>
<select id="selectChildrenByParent" resultMap="newsLabelMapper">
select id,
name from tb_newslabel where pid=#{xxx}
</select>
(2)
<mapper namespace="org.lfz.dao.INewLabelDao">
<select id="selectNewsLabelByParent" resultMap="newsLabelMapper">
select id,name from tb_newslabel where pid=#{xxx}
</select>
<resultMap type="NewsLabel" id="newsLabelMapper" >
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="children"
ofType="NewsLabel"
select="selectNewsLabelByParent"
column="id"/>
</resultMap>
<select id="selectNewsLabelById" resultMap="newsLabelMapper">
select id,
name from tb_newslabel where id=#{xxx}
</select>
</mapper>