java 一种树的写法
左侧菜单树的写法
一 for循环添加
public List<MenuTreeVo> list(String pid, String menuGroup) { List<MenuTreeVo> pList=new ArrayList(); Map<String, MenuTreeVo>map=new HashMap<>(); List<MenuTreeVo> list=menuTreeMapper.list(pid,menuGroup); for(MenuTreeVo menuTreeVo:list){ if(StringUtils.isEmpty(menuTreeVo.getPid())||"0".equals(menuTreeVo.getPid())){ pList.add(menuTreeVo); } map.put(menuTreeVo.getId(),menuTreeVo); } for(MenuTreeVo menuTreeVo:list){ if(!StringUtils.isEmpty(menuTreeVo.getPid())){ MenuTreeVo pMenuTreeVo=map.get(menuTreeVo.getPid()); if(pMenuTreeVo!=null){ if(pMenuTreeVo.getChildrens()==null){ pMenuTreeVo.setChildrens(new ArrayList<>()); } pMenuTreeVo.getChildrens().add(menuTreeVo); } } } return pList; }
第一次for循环将父级元素存到list 并将所有元素存到map
第二次for循环将map中的元素根据pid存放到父级元素中
二 mybatis中sql语句
<select id="list2" resultMap="MenuTreeVotMap2"> SELECT id, pid, name, url, menu_key, order_num, date_format(create_time,'%Y-%m-%d %H:%i:%s') as create_time, date_format(update_time,'%Y-%m-%d %H:%i:%s') as date_format, account, LEVEL, menu_group, component FROM sys_menu_tree_table <where> <if test="pid==null and ''==pid"> and pid = '0' </if> <if test="null!=pid and ''!= pid"> and pid=#{pid} </if> <if test="null!=menuGroup and ''!= menuGroup"> and menu_group=#{menuGroup} </if> </where> order by order_num </select>
<resultMap id="MenuTreeVotMap2" type="com.zqny.core.module.common.vo.MenuTreeVo"> <id column="id" jdbcType="VARCHAR" property="id" /> <result column="pid" jdbcType="VARCHAR" property="pid" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="url" jdbcType="VARCHAR" property="url" /> <result column="menu_key" jdbcType="VARCHAR" property="menuKey" /> <result column="order_num" jdbcType="INTEGER" property="orderNum" /> <result column="create_time" jdbcType="TIMESTAMP" property="createTime" /> <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" /> <result column="account" jdbcType="VARCHAR" property="account" /> <result column="level" jdbcType="INTEGER" property="level" /> <result column="menu_group" jdbcType="VARCHAR" property="menuGroup" /> <result column="component" jdbcType="VARCHAR" property="component" /> <collection property="childrens" ofType="MenuTreeVotMap2" javaType="java.util.List" select="com.zqny.core.mapper.MenuTreeMapper.list2" column="{pid=id,menuGroup=menu_group}"> </collection> </resultMap>
通过collection来继续调用sql语句达到树状分支的目的