Java递归查询菜单树所有节点-返回单层列表

数据库表

查询结果展示

Java递归方法

 /**
     *
     * @param pid 父菜单ID
     * @return
     */
    public List<WsMenu> selectOneList(Integer pid) {
        //fList是递归查询条件
        List<Integer> fList = new ArrayList<Integer>();
        fList.add(pid);
        //查询是递归返回结果sumList
        List<Integer> sumList = new ArrayList<Integer>();
        //然后执行数据库查询,最终返回list
        List<Integer> list =  recursion(fList,sumList);

        return wsMenuMapper.selectOneList(list);
    }

    /**
     *
     * @param fList 初始化的父级ID
     * @param sumList 保存的全部ID
     * @return
     */
    public List<Integer> recursion(List<Integer> fList,List<Integer> sumList) {

        List<Integer> sonIdList = wsMenuMapper.selectIdList(fList);
        if (sonIdList.size()==0){
            return sumList;
        }
        sumList.addAll(sonIdList);
        return recursion(sonIdList,sumList);
    }

mybatis 查询语句

<!--查询所有子集ID-->
    <select id="selectIdList" resultType="Integer" >
         select id from ws_menu where pid in
        (
        <foreach collection ="list" item="item" index= "index" separator =",">
          #{item}
        </foreach>
        )
    </select>

    <!--查询所有自己对象列表-->
    <select id="selectOneList" resultType="com.cloudtop.demo19.model.WsMenu" >
        select * from ws_menu where id in
        (
        <foreach collection ="list" item="item" index= "index" separator =",">
            #{item}
        </foreach>
        )
        order by field
        (id,
        <foreach collection ="list" item="item" index= "index" separator =",">
            #{item}
        </foreach>
        )
    </select>
发布了51 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m0_37882063/article/details/88641906