java树形查询

在这之前呢,我专门写了一个转换为树形查询的工具类,po出来:

public class TransUtil {

    private TransUtil() {}

    /**
     * listToTree
     * 

方法说明

* 将JSONArray数组转为树状结构 * @param arr 需要转化的数据 * @param id 数据唯一的标识键值 * @param pid 父id唯一标识键值 * @param child 子节点键值 * @return JSONArray */ public static JSONArray listToTree(JSONArray arr, String id, String pid, String child){ JSONArray r = new JSONArray(); JSONObject hash = new JSONObject(); //将数组转为Object的形式,key为数组中的id for(int i=0;i<arr.size();i++){ JSONObject json = (JSONObject) arr.get(i); hash.put(json.getString(id), json); } //遍历结果集 for(int j=0;j<arr.size();j++){ //单条记录 JSONObject aVal = (JSONObject) arr.get(j); //在hash中取出key为单条记录中pid的值 JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString()); //如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中 if(hashVP!=null){ //检查是否有child属性 if(hashVP.get(child)!=null){ JSONArray ch = (JSONArray) hashVP.get(child); ch.add(aVal); hashVP.put(child, ch); }else{ JSONArray ch = new JSONArray(); ch.add(aVal); hashVP.put(child, ch); } }else{ r.add(aVal); } } return r; } }

controller层:

@GetMapping("/getTree")
public String getTree(){
    JSONArray result = dbDmsAlgorithmManageClassifyService.getTree();
    if(result == null) {
        return ResponseWrapperUtil.executeCustomTips("false", "查询无数据");
    }
    return ResponseWrapperUtil.executeResultEntity(result);
}

这层不用多解释了吧,ResponseWrapperUtil,这个是我自己弄的返回封装类,你也可以直接返回,问题都不太大。

serviceImpl层:

实现层其实就两行,究极简单。

public JSONArray getTree() {
        //排序查询所有数据,转换为树形结构数据返回。

        List<DbDmsAlgorithmManageClassifyDTO> allByOrderBySeqAsc = dbDmsAlgorithmManageClassifyDAO.findAllByOrderBySeqAsc();
        return TransUtil.listToTree(JSON.parseArray(JSON.toJSONString(allByOrderBySeqAsc)),"id","prentId","children");
        }

方法体力放的"id"啥的不用解释了吧,"prentId"打错了(别人创建数据库的时候就错了,我这里将错就错),这个对应具体数据库里那个parentId的字段名。

service就不放了吧,懒得放了,而且根据实现层大家也肯定都知道。

全剧终。

你可能感兴趣的:(java,sql,java,开发语言,后端)