Mybatis 递归子查询遇见的问题

在运用Springboot +springcloud+mybatis项目中,在菜单列表的三级查询中运用到mybatis递归子查询,然而在查询的时候,有好几次只执行了第一次查询,第二次子菜单不显示。

因为一直想着这个问题,做梦想到了这个问题的关键

<!-- 查询一级菜单权限返回VOTwo -->
 <resultMap id="allMenuMap" type="net.cqnews.hlzycf.common.vo.MenuVO">
  <id property="strMenuId" column="strMenuId" /> <!-- 菜单ID -->
  <result property="strMenuName" column="strMenuName"/> <!-- 菜单名称 -->
  <result property="strMenuIcon" column="strMenuIcon"/> <!-- 菜单图标 -->
  <result property="strMenuIconValue" column="strMenuIconValue"/> <!-- 菜单图标值 -->
  <result property="strMenuUrl" column="strMenuUrl"/> <!-- 路径-->
  <result property="strMenuStatus" column="strMenuStatus"/> <!-- 菜单状态 -->
  <collection property="childList" column="strMenuId" select="twoMenuByPid" /> <!-- 子菜单 -->
 </resultMap>
 
 <!-- 查询所有菜单权限 -->
 <select id="listMenu" parameterType="string" resultMap="allMenuMap">
     SELECT strMenuId, strMenuName, strMenuIcon, strMenuIconValue, strMenuUrl, strMenuStatus FROM tb_menu
  WHERE strOrgStructCode=#{strOrgStructCode} AND strMenuPid='' ORDER BY intSortWeight, strLevelCode
 </select>
 <!-- 根据父ID查询二级菜单权限 -->
 <select id="twoMenuByPid" parameterType="string" resultMap="allMenuMap">
     SELECT strMenuId, strMenuName, strMenuIcon, strMenuIconValue, strMenuUrl, strMenuStatus FROM tb_menu
  WHERE strMenuPid=#{strMenuId} ORDER BY intSortWeight, strLevelCode
 </select> 

这里在collection调用方法里面的column值需要在map里面定义清楚,如果不定义,子查询将不执行,在定义这个property的时候,还需要实体类有定义。


 更多技术交流QQ群:260292706

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
MyBatis 进行递归查询可以使用递归语句(Recursive Statement)或递归查询(Recursive Query)来实现。 如果你使用的是 MySQL 数据库,可以使用递归语句来实现。以下是一个示例: ```xml <select id="selectById" resultMap="resultMap"> with recursive cte as ( select * from department where id = #{id} union all select d.* from department d join cte on d.parent_id = cte.id ) select * from cte </select> ``` 上面的代码,使用 with recursive 声明了一个递归查询语句,查询了 id 等于参数值的部门及其子部门。递归查询语句的第一个 select 查询了初始部门,使用 union all 连接了一个子查询,该子查询使用 join 连接了部门表本身,查询了该部门的子部门。 如果你使用的是 Oracle 数据库,可以使用递归查询来实现。以下是一个示例: ```xml <select id="selectById" resultMap="resultMap"> select * from ( with cte(id, name, parent_id) as ( select id, name, parent_id from department where id = #{id} union all select d.id, d.name, d.parent_id from department d join cte on d.parent_id = cte.id ) select * from cte order by level desc ) where rownum = 1 </select> ``` 上面的代码,使用 with 声明了一个递归查询语句,查询了 id 等于参数值的部门及其子部门。递归查询语句的第一个 select 查询了初始部门,使用 union all 连接了一个子查询,该子查询使用 join 连接了部门表本身,查询了该部门的子部门。最终的 select 语句使用了 order by 和 rownum 来获取最深层级的部门。 需要注意的是,递归查询语句的性能可能会受到影响,因此在实际使用需要进行优化和测试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值