_017_MyBatis_自关联查询_一对多方式实现

   1、 所谓自关联是指,自己即充当一方,又充当多方,是 1:n 或 n:1 的变型。例如,对于新
闻栏目 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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值