欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > MySQL数据库树状结构查询

MySQL数据库树状结构查询

2024/10/24 11:18:53 来源:https://blog.csdn.net/qq_53433105/article/details/140219962  浏览:    关键词:MySQL数据库树状结构查询

一、树状结构

MySQL数据库本身并不直接支持树状结构的存储,但它提供了足够的灵活性,允许我们通过不同的方法来模拟和实现树状数据结构。具体方法看下文。

数据库表结构:

实现效果

查询的结果像树一样

 二、使用

以Catalog数据表,findAll()方法举例

2.1 controller

@RestController
@RequestMapping("catalog")
public class CatalogController {@Autowiredprivate CatalogService catalogService;@GetMapping("findAll")public Result findAll(){return Result.success(catalogService.findAll());}
}

2.2service

public interface CatalogService {List<Catalog> findAll();
}
@Service
public class CatalogServiceImpl implements CatalogService {@Autowiredprivate CatalogMapper catalogMapper;@Overridepublic List<Catalog> findAll() {
//     在这里直接调用findByParentId()方法,等于说mapper的findAll()没用了return catalogMapper.findByParentId(0);}}

2.3mapper--有findAll()方法继承了BaseMapper

public interface CatalogMapper extends BaseMapper<Catalog> {List<Catalog> findByParentId(Integer parentId);
}

 <collection property="studentCatalog" select="findByParentId" column="id">

利用递归函数,父节点id作为参数,直到没有父节点id结束

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itqq.mapper.CatalogMapper"><resultMap id="catalog" type="Catalog"><id property="id" column="id"></id><result property="name" column="name"></result><result property="parentId" column="parent_id"></result><collection property="studentCatalog" select="findByParentId" column="id"></collection></resultMap>
<!--不用也行,可以在CatalogServiceImpl,直接调用findByParentId传id=0就行--><select id="findAll" resultMap="catalog">SELECT * FROM catalog where parent_id = 0</select><select id="findByParentId" resultMap="catalog">select * from catalog where parent_id = #{parentId}</select>
</mapper>

2.4pojo

@Data
public class Catalog implements Serializable {private static final long serialVersionUID = 152326L;private int id;private String name;private String parentId;private List<Catalog> studentCatalog;
}

总结结束,使用时可以按需修改!!!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com