精华内容
下载资源
问答
  • java递归构建树形结构

    千次阅读 2019-02-26 13:50:51
    * 递归算法解析成形结构 * * @param cid * @return * @author jiqinlin */ public TreeNode recursiveTree(int cid) { //根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?) TreeNode node = ...

    只有一个根节点数据结构:

    1、准备表结构及对应的表数据
    a、表结构:

    create table TB_TREE
    (
    CID NUMBER not null,
    CNAME VARCHAR2(50),
    PID NUMBER //父节点
    )

    b、表数据:

    复制代码

    insert into tb_tree (CID, CNAME, PID) values (1, '中国', 0);
    insert into tb_tree (CID, CNAME, PID) values (2, '北京市', 1);
    insert into tb_tree (CID, CNAME, PID) values (3, '广东省', 1);
    insert into tb_tree (CID, CNAME, PID) values (4, '上海市', 1);
    insert into tb_tree (CID, CNAME, PID) values (5, '广州市', 3);
    insert into tb_tree (CID, CNAME, PID) values (6, '深圳市', 3);
    insert into tb_tree (CID, CNAME, PID) values (7, '海珠区', 5);
    insert into tb_tree (CID, CNAME, PID) values (8, '天河区', 5);
    insert into tb_tree (CID, CNAME, PID) values (9, '福田区', 6);
    insert into tb_tree (CID, CNAME, PID) values (10, '南山区', 6);
    insert into tb_tree (CID, CNAME, PID) values (11, '密云县', 2);
    insert into tb_tree (CID, CNAME, PID) values (12, '浦东', 4);

    复制代码

    2、TreeNode对象,对应tb_tree

    复制代码

    public class TreeNode implements Serializable {
    private Integer cid;
    private String cname;
    private Integer pid;
    private List nodes = new ArrayList();
     
    public TreeNode() {
    }
     
    //getter、setter省略
    }

    复制代码

    3、测试数据

    复制代码

    public class TreeNodeTest {
    @Test
    public void loadTree() throws Exception{
    System.out.println(JsonUtils.javaToJson(recursiveTree(1)));
    }
     
    /**
    * 递归算法解析成树形结构
    *
    * @param cid
    * @return
    * @author jiqinlin
    */
    public TreeNode recursiveTree(int cid) {
    //根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
    TreeNode node = personService.getreeNode(cid);
    //查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
    List childTreeNodes = personService.queryTreeNode(cid); 
    //遍历子节点
    for(TreeNode child : childTreeNodes){
    TreeNode n = recursiveTree(child.getCid()); //递归
    node.getNodes().add(n);
    }
     
    return node;
    }
    }

    复制代码

    输出的json格式如下:

    复制代码

    {
        "cid": 1,
        "nodes": [
            {
                "cid": 2,
                "nodes": [
                    {
                        "cid": 11,
                        "nodes": [
                             
                        ],
                        "cname": "密云县",
                        "pid": 2
                    }
                ],
                "cname": "北京市",
                "pid": 1
            },
            {
                "cid": 3,
                "nodes": [
                    {
                        "cid": 5,
                        "nodes": [
                            {
                                "cid": 7,
                                "nodes": [
                                     
                                ],
                                "cname": "海珠区",
                                "pid": 5
                            },
                            {
                                "cid": 8,
                                "nodes": [
                                     
                                ],
                                "cname": "天河区",
                                "pid": 5
                            }
                        ],
                        "cname": "广州市",
                        "pid": 3
                    },
                    {
                        "cid": 6,
                        "nodes": [
                            {
                                "cid": 9,
                                "nodes": [
                                     
                                ],
                                "cname": "福田区",
                                "pid": 6
                            },
                            {
                                "cid": 10,
                                "nodes": [
                                     
                                ],
                                "cname": "南山区",
                                "pid": 6
                            }
                        ],
                        "cname": "深圳市",
                        "pid": 3
                    }
                ],
                "cname": "广东省",
                "pid": 1
            },
            {
                "cid": 4,
                "nodes": [
                    {
                        "cid": 12,
                        "nodes": [
                             
                        ],
                        "cname": "浦东",
                        "pid": 4
                    }
                ],
                "cname": "上海市",
                "pid": 1
            }
        ],
        "cname": "中国",
        "pid": 0
    }

    有多个根节点的树形结构:

    package com.forchain.platform.model;
    
    import javax.persistence.*;
    
    @Table(name = "tb_tree")
    public class TbTree {
    
        @Id
        private Long cid;
    
        @Column(name = "CNAME")
        private String cname;
    
        @Column(name = "PID")
        private Long pid;
    
        /**
         * @return CID
         */
        public Long getCid() {
            return cid;
        }
    
        /**
         * @param cid
         */
        public void setCid(Long cid) {
            this.cid = cid;
        }
    
        /**
         * @return CNAME
         */
        public String getCname() {
            return cname;
        }
    
        /**
         * @param cname
         */
        public void setCname(String cname) {
            this.cname = cname;
        }
    
        /**
         * @return PID
         */
        public Long getPid() {
            return pid;
        }
    
        /**
         * @param pid
         */
        public void setPid(Long pid) {
            this.pid = pid;
        }
    }
    /**
     * author   chong
     * 创建日期: 2019/2/26
     * 创建时间: 12:35
     */
    @Getter
    @Setter
    public class TreeNode extends TbTree implements Serializable {
    
        List<List<TreeNode>> nodeList = new ArrayList<>();
    
    }
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.forchain.platform.mapper.TbTreeMapper">
      <resultMap id="BaseResultMap" type="com.forchain.platform.model.TbTree">
        <!--
          WARNING - @mbg.generated
        -->
        <result column="CID" jdbcType="BIGINT" property="cid" />
        <result column="CNAME" jdbcType="VARCHAR" property="cname" />
        <result column="PID" jdbcType="BIGINT" property="pid" />
      </resultMap>
      <select id="queryTreeNode" parameterType="java.lang.Long" resultType="com.forchain.platform.model.TreeNode">
        select * from tb_tree where PID =#{pId}
      </select>
    </mapper>
    package com.forchain.platform.mapper;
    
    import com.forchain.platform.config.mapper.BaseMapper;
    import com.forchain.platform.model.TbTree;
    import com.forchain.platform.model.TreeNode;
    
    import java.util.List;
    
    public interface TbTreeMapper extends BaseMapper<TbTree> {
    
        List<TreeNode> queryTreeNode(Long pId);
    
    }

    create table tb_tree
    (
    CID BIGINT not null,
    CNAME VARCHAR(50),
    PID BIGINT
    )

    insert into tb_tree (CID, CNAME, PID) values (1, '中国', NULL);
    insert into tb_tree (CID, CNAME, PID) values (2, '北京市', NULL);
    insert into tb_tree (CID, CNAME, PID) values (3, '广东省', NULL);
    insert into tb_tree (CID, CNAME, PID) values (4, '上海市', 1);
    insert into tb_tree (CID, CNAME, PID) values (5, '广州市', 1);
    insert into tb_tree (CID, CNAME, PID) values (6, '深圳市', 1);
    insert into tb_tree (CID, CNAME, PID) values (7, '海珠区', 1);
    insert into tb_tree (CID, CNAME, PID) values (8, '天河区', 2);
    insert into tb_tree (CID, CNAME, PID) values (9, '福田区', 2);
    insert into tb_tree (CID, CNAME, PID) values (10, '南山区', 3);
    insert into tb_tree (CID, CNAME, PID) values (11, '密云县', 3);
    insert into tb_tree (CID, CNAME, PID) values (12, '浦东', 3);
    insert into tb_tree (CID, CNAME, PID) values (13, '浦东22', 3);
    insert into tb_tree (CID, CNAME, PID) values (14, '浦东23', 4);
    insert into tb_tree (CID, CNAME, PID) values (15, '浦东24', 4);
    insert into tb_tree (CID, CNAME, PID) values (16, '浦东25', 6);
    insert into tb_tree (CID, CNAME, PID) values (17, '浦东25', 6);
    insert into tb_tree (CID, CNAME, PID) values (18, '浦东25', 6);

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class BcHrPlatformTest {
    
        @Resource
        TbTreeMapper tbTreeMapper;
        @Test
        public void loadTree() {
            System.err.println(JSONObject.toJSONString(recursiveTree(Long.parseLong(String.valueOf(0)))));
        }
    
        /**
         * 递归算法解析成树形结构
         */
        public List<TreeNode> recursiveTree(Long pId) {
            List<TreeNode> treeNodes = tbTreeMapper.queryTreeNode(pId);
            for (TreeNode node:treeNodes) {
                List<TreeNode> treeNodes1 = recursiveTree(node.getCid());
                if (!treeNodes1.isEmpty()) {
                    node.getNodeList().add(treeNodes1);
                }
            }
            return treeNodes;
        }
    }

    [{
        "cid": 1,
        "cname": "中国",
        "nodeList": [
            [{
                "cid": 4,
                "cname": "上海市",
                "nodeList": [
                    [{
                        "cid": 14,
                        "cname": "浦东23",
                        "nodeList": [],
                        "pid": 4
                    }, {
                        "cid": 15,
                        "cname": "浦东24",
                        "nodeList": [],
                        "pid": 4
                    }]
                ],
                "pid": 1
            }, {
                "cid": 5,
                "cname": "广州市",
                "nodeList": [],
                "pid": 1
            }, {
                "cid": 6,
                "cname": "深圳市",
                "nodeList": [
                    [{
                        "cid": 16,
                        "cname": "浦东25",
                        "nodeList": [],
                        "pid": 6
                    }, {
                        "cid": 17,
                        "cname": "浦东25",
                        "nodeList": [],
                        "pid": 6
                    }, {
                        "cid": 18,
                        "cname": "浦东25",
                        "nodeList": [],
                        "pid": 6
                    }]
                ],
                "pid": 1
            }, {
                "cid": 7,
                "cname": "海珠区",
                "nodeList": [],
                "pid": 1
            }]
        ],
        "pid": 0
    }, {
        "cid": 2,
        "cname": "北京市",
        "nodeList": [
            [{
                "cid": 8,
                "cname": "天河区",
                "nodeList": [],
                "pid": 2
            }, {
                "cid": 9,
                "cname": "福田区",
                "nodeList": [],
                "pid": 2
            }]
        ],
        "pid": 0
    }, {
        "cid": 3,
        "cname": "广东省",
        "nodeList": [
            [{
                "cid": 10,
                "cname": "南山区",
                "nodeList": [],
                "pid": 3
            }, {
                "cid": 11,
                "cname": "密云县",
                "nodeList": [],
                "pid": 3
            }, {
                "cid": 12,
                "cname": "浦东",
                "nodeList": [],
                "pid": 3
            }, {
                "cid": 13,
                "cname": "浦东22",
                "nodeList": [],
                "pid": 3
            }]
        ],
        "pid": 0
    }]

    展开全文
  • Java递归构建树形数据结构实现多级树形菜单展示

    万次阅读 热门讨论 2018-06-15 17:46:16
    首先看看需求,形菜单是这样的:根据需求创建数据模型:构造形数据结构:转为json数据看看结构是否正确:打完收工!

    首先看看需求,树形菜单是这样的:


    根据需求创建数据模型:


    构造树形数据结构(Java8环境,Maps和Lists是用了谷歌的guava包):



    转为json数据看看结构是否正确:



    打完收工!



    2018-06-09修改,过滤map改为set



    展开全文
  • 最近做项目要查出所有的产品类型,并且按照一级二姐三级目录的形式以json字符串的形式返回给前端,上网搜了不少,有在数据库中直接查询的,数据库中有形查询的方法格式,在此不多做介绍,如果数据量过大,可能导致...

    最近做项目要查出所有的产品类型,并且按照一级二姐三级目录的形式以json字符串的形式返回给前端,上网搜了不少,有在数据库中直接查询的,数据库中有树形查询的方法格式,在此不多做介绍,如果数据量过大,可能导致查询效率降低
    另一种是在程序内部做处理,话不多说,直接上代码:

    mapper

    ,可以根据自己的需求去查,我因为是需要查询全部产品类型,就都查了

    @Mapper
    public interface TypeTreeMapper extends BaseMapper<TypeTree> {
    
        List<TypeTreeVo> showTypeTree();
    
    }
    

    mapper.xml

        <!-- 通用查询映射结果 -->
        <resultMap id="BaseResultMap" type="com.lookherbs.lookherbscloud.provider.lookherbscloudproviderdmc.common.product.TypeTreeVo">
            <id column="type_id" property="typeId" />
            <result column="type_name" property="typeName" />
            <result column="ename" property="ename" />
            <result column="lname" property="lname" />
            <result column="ftype_id" property="ftypeId" />
            <result column="rtype_id" property="rtypeId" />
            <result column="type_level" property="typeLevel" />
        </resultMap>
    
        <!-- 根据父键查询 -->
        <select id="showTypeTree" resultMap="BaseResultMap">
    	 	select * from t_type_tree
    	 </select>
    

    主要的处理逻辑是在service层

    service

    第一级的父id为0就不多说了,二级三级四级的父id分别就是相对应的上一级的id,用递归去获取查询出来的数据,实体类中创建一个List集合,存放相对应的子集目录下的所有内容,对于lambda有点陌生的可以看我的上一篇博客

     @Override
        public List<TypeTreeVo> showTypeTree() {
            List<TypeTreeVo> nodeList = treeMapper.showTypeTree();
            List<TypeTreeVo> all=nodeList.stream().filter(t->
                    t.getFtypeId()!=null && t.getFtypeId()==0
            ).map((t)->{
                t.setChildren(getFtype(t,nodeList));
                return t;
            }).collect(Collectors.toList());
            return all;
        }
    
        private List<TypeTreeVo> getFtype(TypeTreeVo root,List<TypeTreeVo> all){
           List<TypeTreeVo> children=all.stream().filter(t -> {
                return Objects.equals(t.getFtypeId(),root.getTypeId());
            }).map((t)->{
                t.setChildren(getFtype(t,all));
                return t;
            }).collect(Collectors.toList());
            return children;
        }
    

    controller没啥操作,直接返回就行

     /**
         * 展示产品类型
         * @return
         */
        @RequestMapping("/show")
        public Wrapper showTypeTree(){
            return handleResult(treeService.showTypeTree());
        }
    

    实体类的VO

    @Data
    public class TypeTreeVo implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        //类型id
        private Integer typeId;
    
        private String typeName;
    
        private String ename;
    
        private String lname;
    
        //父类型id
        private Integer ftypeId;
    
        //根类型id
        private Integer rtypeId;
    
        private Integer typeLevel;
    
        List<TypeTreeVo> children;
    
    }
    
    

    看效果

    {
        "code": 200,
        "message": "操作成功",
        "result": [
            {
                "typeId": 1,
                "typeName": "植物原料",
                "ename": "Plant Materials",
                "lname": "zwyl",
                "ftypeId": 0,
                "rtypeId": 0,
                "typeLevel": 1,
                "children": [
                    {
                        "typeId": 2,
                        "typeName": "根",
                        "ename": "gen",
                        "lname": "g",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 3,
                        "typeName": "茎",
                        "ename": "jin",
                        "lname": "j",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 4,
                        "typeName": "叶",
                        "ename": "ye",
                        "lname": "y",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 5,
                        "typeName": "花",
                        "ename": "hua",
                        "lname": "h",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 6,
                        "typeName": "果实",
                        "ename": "guoshi",
                        "lname": "gs",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 7,
                        "typeName": "种子",
                        "ename": "zhognzi",
                        "lname": "zz",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 8,
                        "typeName": "树皮",
                        "ename": "shupi",
                        "lname": "sp",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 9,
                        "typeName": "全草",
                        "ename": "quancao",
                        "lname": "qc",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 10,
                        "typeName": "地上部分",
                        "ename": "dishangbufen",
                        "lname": "dsbf",
                        "ftypeId": 1,
                        "rtypeId": 1,
                        "typeLevel": 2,
                        "children": []
                    }
                ]
            },
            {
                "typeId": 11,
                "typeName": "提取物",
                "ename": "Extracts",
                "lname": "tqw",
                "ftypeId": 0,
                "rtypeId": 0,
                "typeLevel": 1,
                "children": [
                    {
                        "typeId": 12,
                        "typeName": "标准提取物",
                        "ename": "biaozhuntiquwu",
                        "lname": "bztqw",
                        "ftypeId": 11,
                        "rtypeId": 11,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 13,
                        "typeName": "比例提取物",
                        "ename": "bilitiquwu",
                        "lname": "bltqw",
                        "ftypeId": 11,
                        "rtypeId": 11,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 14,
                        "typeName": "有效成分单体",
                        "ename": "youxiaochengfendanti",
                        "lname": "yxcfdt",
                        "ftypeId": 11,
                        "rtypeId": 11,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 15,
                        "typeName": "医药中间体",
                        "ename": "yiyaozhongjianti",
                        "lname": "yyzjt",
                        "ftypeId": 11,
                        "rtypeId": 11,
                        "typeLevel": 2,
                        "children": []
                    }
                ]
            },
            {
                "typeId": 16,
                "typeName": "原料药",
                "ename": "yuanliaoyao",
                "lname": "yly",
                "ftypeId": 0,
                "rtypeId": 0,
                "typeLevel": 1,
                "children": [
                    {
                        "typeId": 30,
                        "typeName": "原料药",
                        "ename": "yuanliaoyao",
                        "lname": "yly",
                        "ftypeId": 16,
                        "rtypeId": 16,
                        "typeLevel": 2,
                        "children": []
                    }
                ]
            },
            {
                "typeId": 17,
                "typeName": "实验室用品",
                "ename": "Laboratory Supplies",
                "lname": "sysyp",
                "ftypeId": 0,
                "rtypeId": 0,
                "typeLevel": 1,
                "children": [
                    {
                        "typeId": 18,
                        "typeName": "检测仪器设备",
                        "ename": "yiqishebei",
                        "lname": "sqsb",
                        "ftypeId": 17,
                        "rtypeId": 17,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 19,
                        "typeName": "试剂耗材",
                        "ename": "shijihaocai",
                        "lname": "sjhc",
                        "ftypeId": 17,
                        "rtypeId": 17,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 20,
                        "typeName": "维护保养",
                        "ename": "weihubaoyao",
                        "lname": "whby",
                        "ftypeId": 17,
                        "rtypeId": 17,
                        "typeLevel": 2,
                        "children": []
                    }
                ]
            },
            {
                "typeId": 21,
                "typeName": "生产相关",
                "ename": "Production Related",
                "lname": "scsb",
                "ftypeId": 0,
                "rtypeId": 0,
                "typeLevel": 1,
                "children": [
                    {
                        "typeId": 22,
                        "typeName": "生产设备",
                        "ename": "shengchanshebei",
                        "lname": "scxg",
                        "ftypeId": 21,
                        "rtypeId": 21,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 23,
                        "typeName": "配件",
                        "ename": "peijian",
                        "lname": "pj",
                        "ftypeId": 21,
                        "rtypeId": 21,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 24,
                        "typeName": "生产技术转让",
                        "ename": "shengwujishuzhuangrang",
                        "lname": "scjszr",
                        "ftypeId": 21,
                        "rtypeId": 21,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 25,
                        "typeName": "整体解决方案",
                        "ename": "zhengtifanganjiejue",
                        "lname": "ztfajj",
                        "ftypeId": 21,
                        "rtypeId": 21,
                        "typeLevel": 2,
                        "children": []
                    }
                ]
            },
            {
                "typeId": 26,
                "typeName": "循环利用",
                "ename": "Cyclic Uutilization",
                "lname": "xhly",
                "ftypeId": 0,
                "rtypeId": 0,
                "typeLevel": 1,
                "children": [
                    {
                        "typeId": 27,
                        "typeName": "水提废弃物",
                        "ename": "shuitifeiqiwu",
                        "lname": "stqufw",
                        "ftypeId": 26,
                        "rtypeId": 26,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 28,
                        "typeName": "醇提废弃物",
                        "ename": "chutifeiqiwu",
                        "lname": "cttqfw",
                        "ftypeId": 26,
                        "rtypeId": 26,
                        "typeLevel": 2,
                        "children": []
                    },
                    {
                        "typeId": 29,
                        "typeName": "其它废料",
                        "ename": "qitafeiliao",
                        "lname": "qtgfl",
                        "ftypeId": 26,
                        "rtypeId": 26,
                        "typeLevel": 2,
                        "children": []
                    }
                ]
            }
        ]
    }
    

    自己各处请教和查询资料才鼓捣出来的东西,难登大雅之堂,不足之处请来喷,哈哈

    展开全文
  • 最近把项目中的形插件换成了bootstrap-treeview,把使用过程中的事情和大家分享一下。 1、下载bootstrap-treeview插件,把css和js引入到项目中 <!-- bootstrap-treeview --> <link rel="stylesheet" ...

    最近把项目中的树形插件换成了bootstrap-treeview,把使用过程中的事情和大家分享一下。

    1、下载bootstrap-treeview插件,把css和js引入到项目中

     <!-- bootstrap-treeview -->
     <link rel="stylesheet" href="${path}/js/bootstrap-treeview/css/bootstrap-treeview.css">
     <!-- bootstrap-treeview -->
    <script src="${path}/js/bootstrap-treeview/js/bootstrap-treeview.js"></script>
    

    2、使用插件构建树形结构

    $.ajax({
    		url:'selectModelList',
    		type:'post',
    		dataType: "json",
    		success:function(result){
    			$('#modelTreeView').treeview({
    				data: result.data,         // 数据源
    				showTags: false,
    				showCheckbox: true,   //是否显示复选框
    				showBorder: false,
    				onhoverColor:"#F9F9F9",
    				selectedBackColor:"#1e9fff",
    				highlightSelected: true,    //是否高亮选中
    				// multiSelect: false,    //多选
    				levels : 1,
    				enableLinks : true,//必须在节点属性给出href属性
    				color: "#010A0E",
    				onNodeChecked : function (event,node) {
    					var selectNodes = getChildNodeIdArr(node); //获取所有子节点
    					if (selectNodes) { //子节点不为空,则选中所有子节点
    						$('#modelTreeView').treeview('checkNode', [selectNodes, { silent: true }]);
    					}
    				},
    				onNodeUnchecked : function(event, node) { //取消选中节点
    					var selectNodes = getChildNodeIdArr(node); //获取所有子节点
    					if (selectNodes) { //子节点不为空,则取消选中所有子节点
    					 	$('#modelTreeView').treeview('uncheckNode', [selectNodes, { silent: true }]);
    					}
    				},
    				onNodeExpanded : function(event, data) {
    				},
    				onNodeSelected: function (event, data) {
    				}
    			})
    		},
    		error: function () {
    			alert("树形结构加载失败!")
    		}
    	})
    

    3、构建bootstrap-treeview需要的数据结构
    bootstrap-treeview需要的数据结构用例

    var defaultData = [
    	{
    		text: '生物质热电联产项目',
    		nodes: [
    			{
    				text: '建筑',
    				nodes: [
    					{
    						text: '站台层建筑',
    					},
    					{
    						text: '展厅层建筑',
    					}
    				]
    			},
    			{
    				text: '结构',
    			}
    		]
    	},
    	{
    		text: '嘉年华站',
    	},
    	{
    		text: '泰山路站',
    	}
    ];
    

    使用JAVA递归,结合Mysql函数为树形结构提供数据
    controller接口

    	/**
    	 * 模型选择
    	 * @return 画面
    	 * @throws Exception 异常
    	 */
    	@RequestMapping(value="/selectModelList")
    	@ResponseBody
    	public ResultModel selectModelList(HttpServletRequest request, Model model) throws Exception{
    		ModelPro modelPro = new ModelPro();
    		modelPro.setModel_parent(0);
    		List<ModelPro> comList = modelService.patchList(modelPro);
    		List<ModelPro> baseList = new ArrayList<ModelPro>();
    		JSONArray ja;
    		if(comList != null && comList.size() > 0){
    			tempModelLst = new ArrayList<ModelPro>();
    			for (ModelPro baseModel : baseList) {
    				tempModelLst = modelService.getAllModelByRootID(baseModel.getId());
    				baseModel.setNodes(editModelLst(baseModel.getId()));
    			}
    		}
    		return ResultModel.success(modelService.listToJson(baseList));
    	}
    

    递归获取下级子

    	/**
    	 * 递归编辑子级模型
    	 * @param model_id 模型id
    	 * @return 结果集
    	 * @throws Exception 异常
    	 */
    	private List<ModelPro> editModelLst(int model_id) {
    		List<ModelPro> retModelLst1 = new ArrayList<ModelPro>();
    		// 取出model_id的下属模型
    		List<ModelPro> modelLst = getTreeModelList(model_id);
    		for (ModelPro model : modelLst) {
    			List<ModelPro> ja = editModelLst(model.getId());
    			// 克隆对象
    			ModelPro newModel = (ModelPro)model.clone();
    			newModel.setNodes(ja);
    			retModelLst1.add(newModel);
    		}
    		return retModelLst1;
    	}
    
    	/**
    	 * 通过模型ID获取下面的直接子级模型
    	 * @param model_id 模型id
    	 * @return 结果集
    	 */
    	private List<ModelPro> getTreeModelList(int model_id) {
    		List<ModelPro> retLst = new ArrayList<ModelPro>();
    		for (ModelPro model : tempModelLst) {
    			if (model.getModel_parent() == model_id) {
    				retLst.add(model);
    			}
    		}
    		return retLst;
    	}
    

    mapper下用到的SQL语句

    	<!-- 获取数据列表 -->
    	<select id="patchList" resultMap="BaseResultMap" parameterType="com.dj.bimsys.manager.pojo.ModelPro" >
    		SELECT <include refid="Base_Column_List" />, model_name as text
    		FROM dj_model
    		WHERE if_delete = 'T' and model_parent = #{model_parent,jdbcType=INTEGER}
    		ORDER BY model_sort ASC,id DESC
    	</select>
    
    	<!-- 通过parentid获取下面所有的id -->
    	<select id="getAllModelByRootID" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    		SELECT <include refid="Page_Column_List" />, c.model_name as text
    		FROM dj_model c
    		WHERE FIND_IN_SET(c.id, getChildLst(#{modelId}))
    		ORDER BY c.model_parent ASC, c.id ASC
    	</select>
    

    SQL语句中使用的自定义函数getChildLst

    BEGIN
        DECLARE sTemp VARCHAR(1000);
        DECLARE sTempChd VARCHAR(1000);
        SET sTemp = '$';
        SET sTempChd =cast(rootId as CHAR);
    
        WHILE sTempChd is not null DO
          SET sTemp = concat(sTemp,',',sTempChd);
          SELECT group_concat(id) INTO sTempChd FROM dj_model where FIND_IN_SET(model_parent, sTempChd)>0;
        END WHILE; 
      RETURN sTemp;
    END
    

    4、通过以上的数据,bootstrap-treeview的最终展示效果
    在这里插入图片描述

    展开全文
  • java递归构建菜单

    2019-10-03 04:05:28
    1 package testSimple; 2 ... 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class BuildTree { 7 public static void main(String[] args) { 8 List<Tre...
  • 这是他的其他一些文章:面试阿里前,问问自己能不能手写这道题面试被问到Spring IOC、AOP和动态代理,用这篇文章怼过去面试被问到Java虚拟机,用这篇文章怼过去正文题目要求:现在我们拥有全国的省、市、县、镇的...

空空如也

空空如也

1 2 3 4 5 ... 7
收藏数 140
精华内容 56
关键字:

java递归构建树

java 订阅