文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

树形结构查询

2023-09-05 14:05

关注

提示:以下内容仅供参开

文章目录


前言

提示:


提示:以下是本篇文章正文内容,下面案例可供参考

一、需求场景

实际开发中,后端需要返回树形结构数据,比如:部门树

二、数据库表

表结构展示:
数据库表结构

三.实现方式

1.方式1:

方式1是通过mybatis的递归查询实现

代码如下(示例):

实体类对象:

@TableName(value ="t_department")@Datapublic class Department implements Serializable {        @TableId(value = "id", type = IdType.AUTO)    private Integer id;        @TableField(value = "name")    private String name;        @TableField(value = "parentId")    private Integer parentId;        @TableField(value = "depPath")    private String depPath;        @TableField(value = "enabled")    private Integer enabled;        @TableField(value = "isParent")    private Integer isParent;    @TableField(exist = false)    private List<Department> children;    @TableField(exist = false)    private static final long serialVersionUID = 1L;}

mapper层代码:

public interface DepartmentMapper extends BaseMapper<Department> {    List<Department> getAllById(Integer id);}

service层

@Override    public List<Department> getAll() {        return departmentMapper.getAllById(-1);    }

xml展示:

<resultMap id="BaseResultMap" type="org.example.domain.Department">           <id property="id" column="id" jdbcType="INTEGER"/>           <result property="name" column="name" jdbcType="VARCHAR"/>           <result property="parentId" column="parentId" jdbcType="INTEGER"/>           <result property="depPath" column="depPath" jdbcType="VARCHAR"/>           <result property="enabled" column="enabled" jdbcType="TINYINT"/>           <result property="isParent" column="isParent" jdbcType="TINYINT"/>   </resultMap>   <resultMap id="DepartmentMap" type="org.example.domain.Department" extends="BaseResultMap">       <collection property="children" ofType="org.example.domain.Department" column="id"                   select="org.example.mapper.DepartmentMapper.getAllById">       </collection>   </resultMap>   <sql id="Base_Column_List">       id,name,parentId,       depPath,enabled,isParent   </sql>   <select id="getAllById" resultMap="DepartmentMap">       select <include refid="Base_Column_List" />       from t_department       where parentId = #{id}   </select>

主要是通过collection标签实现递归查询,首先查询根节点,然后返回的id依次去查询子节点

测试:

 @Test    public void testGetDepartments1(){        List<Department> list = departmentService.getAll();        System.out.println(JSON.toJSONString(list));    }

输出结果:

==>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==> Parameters: -1(Integer)<==    Columns: id, name, parentId, depPath, enabled, isParent<==        Row: 1, 股东会, -1, .1, 1, 1====>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?====> Parameters: 1(Integer)<====    Columns: id, name, parentId, depPath, enabled, isParent<====        Row: 2, 董事会, 1, .1.2, 1, 1======>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?======> Parameters: 2(Integer)<======    Columns: id, name, parentId, depPath, enabled, isParent<======        Row: 3, 总办, 2, .1.2.3, 1, 1========>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?========> Parameters: 3(Integer)<========    Columns: id, name, parentId, depPath, enabled, isParent<========        Row: 4, 财务部, 3, .1.2.3.4, 1, 0==========>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==========> Parameters: 4(Integer)<==========      Total: 0<========        Row: 5, 市场部, 3, .1.2.3.5, 1, 1==========>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==========> Parameters: 5(Integer)<==========    Columns: id, name, parentId, depPath, enabled, isParent<==========        Row: 6, 华东市场部, 5, 1.2.3.5.6, 1, 1============>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?============> Parameters: 6(Integer)<============    Columns: id, name, parentId, depPath, enabled, isParent<============        Row: 8, 上海市场部, 6, 1.2.3.5.6.8, 1, 0==============>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==============> Parameters: 8(Integer)<==============      Total: 0<============      Total: 1<==========        Row: 7, 华南市场部, 5, 1.2.3.5.7, 1, 0============>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?============> Parameters: 7(Integer)<============      Total: 0<==========        Row: 9, 西北市场部, 5, .1.2.3.5.9, 1, 1============>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?============> Parameters: 9(Integer)<============    Columns: id, name, parentId, depPath, enabled, isParent<============        Row: 10, 贵阳市场, 9, .1.2.3.5.9.10, 1, 1==============>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==============> Parameters: 10(Integer)<==============    Columns: id, name, parentId, depPath, enabled, isParent<==============        Row: 11, 乌当区市场, 10, .1.2.3.5.9.10.11, 1, 0================>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?================> Parameters: 11(Integer)<================      Total: 0<==============      Total: 1<============      Total: 1<==========      Total: 3<========        Row: 12, 技术部, 3, .1.2.3.12, 1, 0==========>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==========> Parameters: 12(Integer)<==========      Total: 0<========        Row: 13, 运维部, 3, .1.2.3.13, 1, 0==========>  Preparing: select id,name,parentId, depPath,enabled,isParent from t_department where parentId = ?==========> Parameters: 13(Integer)<==========      Total: 0<========      Total: 4<======      Total: 1<====      Total: 1<==      Total: 1Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@437281c5][{"children":[{"children":[{"children":[{"children":[],"depPath":".1.2.3.4","enabled":1,"id":4,"isParent":0,"name":"财务部","parentId":3},{"children":[{"children":[{"children":[],"depPath":"1.2.3.5.6.8","enabled":1,"id":8,"isParent":0,"name":"上海市场部","parentId":6}],"depPath":"1.2.3.5.6","enabled":1,"id":6,"isParent":1,"name":"华东市场部","parentId":5},{"children":[],"depPath":"1.2.3.5.7","enabled":1,"id":7,"isParent":0,"name":"华南市场部","parentId":5},{"children":[{"children":[{"children":[],"depPath":".1.2.3.5.9.10.11","enabled":1,"id":11,"isParent":0,"name":"乌当区市场","parentId":10}],"depPath":".1.2.3.5.9.10","enabled":1,"id":10,"isParent":1,"name":"贵阳市场","parentId":9}],"depPath":".1.2.3.5.9","enabled":1,"id":9,"isParent":1,"name":"西北市场部","parentId":5}],"depPath":".1.2.3.5","enabled":1,"id":5,"isParent":1,"name":"市场部","parentId":3},{"children":[],"depPath":".1.2.3.12","enabled":1,"id":12,"isParent":0,"name":"技术部","parentId":3},{"children":[],"depPath":".1.2.3.13","enabled":1,"id":13,"isParent":0,"name":"运维部","parentId":3}],"depPath":".1.2.3","enabled":1,"id":3,"isParent":1,"name":"总办","parentId":2}],"depPath":".1.2","enabled":1,"id":2,"isParent":1,"name":"董事会","parentId":1}],"depPath":".1","enabled":1,"id":1,"isParent":1,"name":"股东会","parentId":-1}]

部门树结构:

[    {        "children":[            {                "children":[                    {                        "children":[{    "children":[    ],    "depPath":".1.2.3.4",    "enabled":1,    "id":4,    "isParent":0,    "name":"财务部",    "parentId":3},{    "children":[        {            "children":[                {                    "children":[                    ],                    "depPath":"1.2.3.5.6.8",                    "enabled":1,                    "id":8,                    "isParent":0,                    "name":"上海市场部",                    "parentId":6                }            ],            "depPath":"1.2.3.5.6",            "enabled":1,            "id":6,            "isParent":1,            "name":"华东市场部",            "parentId":5        },        {            "children":[            ],            "depPath":"1.2.3.5.7",            "enabled":1,            "id":7,            "isParent":0,            "name":"华南市场部",            "parentId":5        },        {            "children":[                {                    "children":[                        {"children":[],"depPath":".1.2.3.5.9.10.11","enabled":1,"id":11,"isParent":0,"name":"乌当区市场","parentId":10                        }                    ],                    "depPath":".1.2.3.5.9.10",                    "enabled":1,                    "id":10,                    "isParent":1,                    "name":"贵阳市场",                    "parentId":9                }            ],            "depPath":".1.2.3.5.9",            "enabled":1,            "id":9,            "isParent":1,            "name":"西北市场部",            "parentId":5        }    ],    "depPath":".1.2.3.5",    "enabled":1,    "id":5,    "isParent":1,    "name":"市场部",    "parentId":3},{    "children":[    ],    "depPath":".1.2.3.12",    "enabled":1,    "id":12,    "isParent":0,    "name":"技术部",    "parentId":3},{    "children":[    ],    "depPath":".1.2.3.13",    "enabled":1,    "id":13,    "isParent":0,    "name":"运维部",    "parentId":3}                        ],                        "depPath":".1.2.3",                        "enabled":1,                        "id":3,                        "isParent":1,                        "name":"总办",                        "parentId":2                    }                ],                "depPath":".1.2",                "enabled":1,                "id":2,                "isParent":1,                "name":"董事会",                "parentId":1            }        ],        "depPath":".1",        "enabled":1,        "id":1,        "isParent":1,        "name":"股东会",        "parentId":-1    }]

2.方式2:

方式2是通过java的递归查询实现
代码如下(示例):

    @Override    public List<Department> getAll2() {//        查询全部部门        List<Department> list = departmentMapper.selectList(null);//        获取根节点        List<Department> Departments = list.stream()                .filter(e -> e.getParentId()==-1)                .map(e -> {                    e.setChildren(getChildrens(e, list));                    return e;                }).collect(Collectors.toList());        return Departments;    }        private List<Department> getChildrens(Department e, List<Department> list) {        List<Department> children = list.stream()                .filter(m -> Objects.equals(e.getId(), m.getParentId()))                .map(m -> {                    m.setChildren(getChildrens(m, list));                    return m;                }).collect(Collectors.toList());        return children;    }

测试结果同上:

@Test    public void testGetDepartments2(){        List<Department> list = departmentService.getAll2();        System.out.println(JSON.toJSONString(list));    }

在这里插入图片描述
笔者推荐第二种方式,数据库只查询一次。

总结

来源地址:https://blog.csdn.net/weixin_36870769/article/details/128638316

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-数据库
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯