JAVA根据条件查询出树结构的数据

需求是根据调度中心的id一层一层的查询出最顶层的数据。

JAVA根据条件查询出树结构的数据_第1张图片

表结构有层级关系,parentId:

这个地方查询的时候涉及到动态sql,每次查询都需要更改sql的查询信息》

server:代码:

public List findByRoleId(String roleId) {
        List functions=new ArrayList();
        Set functionSet=new HashSet();
        //先查询出最大节点数
        Integer maxLevel = functionDao.selectMaxLevel(roleId);
        if(maxLevel==null){
            return functions;
        }
        String replaceOldStr="select * ";
        String replaceNewStr="select * from tb_sys_function where id in (select parent_id ";
        String addStr=")";
        //第一次
        String sql="select * from tb_sys_function where id IN ( SELECT function_id FROM tb_sys_role_function WHERE role_id = ? ) ORDER BY LEVEL, order_num";
        List firstFunctions=jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Function.class), roleId);
        if(firstFunctions!=null&&firstFunctions.size()>0){
            functionSet.addAll(firstFunctions);
        }
        //执行第二次查询
        for(int i=2;i<=maxLevel;i++){
            sql=sql.replace(replaceOldStr, replaceNewStr)+addStr;
            List bianFunctions= jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Function.class), roleId);
            if(bianFunctions!=null&&bianFunctions.size()>0){
                functionSet.addAll(bianFunctions);
            }
        }
        //去重
        Iterator itor=functionSet.iterator();
        while(itor.hasNext()){
            Function function=itor.next();
            functions.add(function);
        }
        return functions;
    }

最后执行的sql语句有:

JAVA根据条件查询出树结构的数据_第2张图片

主要就是动态的改变sql,一级一级的根据parentId遍历查询出数据。

你可能感兴趣的:(java)