SpringBoot+Mybatis实现父子节点递归查询,细到极致

大家晚上好,我是专业过硬,从未翻车的Jessica老哥。最近有个需求,需要实现一个类似父子节点查询的功能,我找了找网上的文章,很难找到一篇实用的父子查询。
  所以,老哥站出来,用最简单的方式,实现一次父子节点的递归查询。
  话不多说,开始编码
1、常规操作,导入依赖,编写配置
有些年轻人,看我写这些简单的,觉得没意思,老哥认为你千万不要这样想,简单的事情重复做,是非常有用的,这些会让你以后得心应手做这些基础的工作。

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-autoconfigure</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        
        <dependency>
          <groupId>cn.hutool</groupId>
          <artifactId>hutool-all</artifactId>
          <version>5.6.5</version>
       </dependency>
        
spring:
  web:
    resources:
      static-locations: classpath:/META-INF/resources/, classpath:/static/,classpath:/templates/
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
    username: root
    password: root

#mybatis-plus配置控制台打印完整带参数SQL语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.dowhere.pojo

2、生成表
DROP TABLE IF EXISTS tree_table;
CREATE TABLE tree_table (
id int(0) NOT NULL AUTO_INCREMENT COMMENT ‘主键ID’,
code varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘编码’,
name varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘名称’,
parent_code varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ‘父级编码’,
PRIMARY KEY (id) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = ‘树形结构测试表’ ROW_FORMAT = Dynamic;

INSERT INTO tree_table VALUES (1, ‘10000’, ‘电脑’, ‘0’);
INSERT INTO tree_table VALUES (2, ‘10001’, ‘华为笔记本’, ‘10000’);
INSERT INTO tree_table VALUES (3, ‘10002’, ‘惠普笔记本’, ‘10000’);
INSERT INTO tree_table VALUES (4, ‘1000101’, ‘标准旗舰系列’, ‘10001’);
INSERT INTO tree_table VALUES (5, ‘1000102’, ‘高端商务系列’, ‘10001’);

3、实体类

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tree_table")
public class TreeTable implements Serializable {

    /**
     * 主键ID
     */
    @TableId(type = IdType.AUTO)
    private Integer id;

    /**
     * 编码
     */
    private String code;

    /**
     * 名称
     */
    private String name;

    /**
     * 父级编码
     */
    private String parentCode;

    /**
     * 子节点
     */
    @TableField(exist = false)
    private List<TreeTable> childNode;
}

3A、mapper接口

@Mapper
public interface TreeTableMapper extends BaseMapper<TreeTable> {
    List<TreeTable> noteTree();
}

5、在resources文件夹下,新建一个mapper包,然后写个 TreeTableMapper.xml

<?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.dowhere.mapper.TreeTableMapper">

    <resultMap id="BaseResultMap" type="com.dowhere.entity.TreeTable">
        <result column="id" property="id"/>
        <result column="code" property="code"/>
        <result column="name" property="name"/>
        <result column="parent_code" property="parentCode"/>
    </resultMap>
    <resultMap id="NodeTreeResult" type="com.dowhere.entity.TreeTable" extends="BaseResultMap">
<!--        ofType:返回类型-->
        <collection property="childNode" column="code" ofType="com.dowhere.entity.TreeTable"
                    javaType="java.util.ArrayList" select="nextNoteTree">
        </collection>
    </resultMap>

    <sql id="Base_Column_List">
        id,
        code,
        name,
        parent_code
    </sql>

<!--    nextNoteTree:循环获取子节点数据,知道叶子节点结束;-->
    <select id="nextNoteTree" resultMap="NodeTreeResult">
        select
        <include refid="Base_Column_List"/>
        from tree_table
        where parent_code=#{code}
    </select>

<!--    noteTree :获取所有父级节点数据-->
    <select id="noteTree" resultMap="NodeTreeResult">
        select
        <include refid="Base_Column_List"/>
        from tree_table
        where parent_code='0'
    </select>

</mapper>

6、新建一个测试类 ApplicationTests

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @Autowired
    private TreeTableMapper treeTableMapper;
 
   @Test
    public void testTreeNode(){
        List<TreeTable> treeTables = treeTableMapper.noteTree();
        String s = JSONUtil.toJsonPrettyStr(treeTables);
        System.out.println(s);
    }
    
}

7、启动单元测试,成功打印
在这里插入图片描述
8、写到这里,就默默的说一句,屏幕前的各位大帅逼,还有大漂亮,看到这里,麻烦给老哥一个点赞、关注、收藏三连好吗,你的支持是老哥更新最大的动力,谢谢!

  • 17
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
MyBatis是一种基于Java的持久层框架,它提供了许多强大的功能来简化数据库操作。在使用MyBatis进行递归查询时,我们可以通过按ID树进行查询来获取满足条件的结果。 要实现递归查询,我们可以使用MyBatis的循环引用来建立子关系。在数据库表中,我们通常会有一个字段用来存储级ID,以建立树形结构。下面是一个示例表结构: ``` id | name | parentId ----------------------- 1 | A | null 2 | B | 1 3 | C | 1 4 | D | 2 ``` 假设我们要查询以A为根节点的树形结构,可以通过以下步骤来实现: 1. 创建一个Mapper接口,定义一个方法用于查询以指定ID为根节点的树形结构: ```java public interface TreeMapper { List<Node> queryTreeByParentId(String parentId); } ``` 2. 创建一个ResultMap,用于映射查询结果到对象: ```xml <resultMap id="NodeResultMap" type="com.example.Node"> <id property="id" column="id"/> <result property="name" column="name"/> <association property="children" javaType="java.util.List" resultMap="NodeResultMap"/> </resultMap> ``` 3. 编写SQL语句进行递归查询,可以使用SELECT、JOIN和WHERE等关键字来实现: ```xml <select id="queryTreeByParentId" resultMap="NodeResultMap"> SELECT n1.id, n1.name, n2.id as childId, n2.name as childName FROM my_table n1 LEFT JOIN my_table n2 ON n1.id = n2.parentId WHERE n1.id = #{parentId} </select> ``` 4. 在Mapper接口中实现该方法: ```java public List<Node> queryTreeByParentId(String parentId); ``` 通过以上步骤,我们可以实现根据ID树递归查询的功能。调用该方法时,传入指定的ID,可以获取到满足条件的树形结构。每个节点对象都可以包含一个子节点集合,用于表示树结构。 总结:利用MyBatis的循环引用和ResultMap的嵌套,我们可以很方便地实现根据ID树进行递归查询。这种方式简化了SQL语句的编写,并提供了方便的对象映射功能,使得操作数据库变得更加简单和高效。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jesscia ^_^

您的打赏将是我努力的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值