Java MyBatis-Plus 递归查询实现树状数据结构
Java MyBatis-Plus 递归查询实现树状数据结构
本文将介绍使用 Java 和 MyBatis-Plus 实现父子表递归查询,获取树状数据结构的步骤和代码示例。通过定义实体类、Mapper 接口、Service 层递归方法和 Controller 层调用,最终实现访问接口获取树状数据的功能。
1. 实体类定义
public class ParentChild { private Long id; private String name; private String code; private Long pid; private List<ParentChild> child; // 省略getter和setter方法}2. Mapper 接口定义
public interface ParentChildMapper extends BaseMapper<ParentChild> { List<ParentChild> selectByPid(Long pid);}3. Service 层递归查询方法
@Service public class ParentChildService { @Autowired private ParentChildMapper parentChildMapper; public List<ParentChild> getTreeData() { List<ParentChild> rootList = parentChildMapper.selectByPid(0L); for (ParentChild parent : rootList) { List<ParentChild> childList = getChildList(parent.getId()); parent.setChild(childList); } return rootList; } private List<ParentChild> getChildList(Long parentId) { List<ParentChild> childList = parentChildMapper.selectByPid(parentId); for (ParentChild child : childList) { List<ParentChild> grandchildren = getChildList(child.getId()); child.setChild(grandchildren); } return childList; } }4. Controller 层调用
@RestController public class ParentChildController { @Autowired private ParentChildService parentChildService; @GetMapping("/treeData") public List<ParentChild> getTreeData() { return parentChildService.getTreeData(); } }当访问"/treeData"接口时,就可以获取到树状数据了。
原文地址: https://www.cveoy.top/t/topic/qhQo 著作权归作者所有。请勿转载和采集!