表结构
CREATE TABLE `test2` (
`id` varchar(32) DEFAULT NULL,
`prarentid` varchar(32) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
实体类
@Data
public class Test2 {
private String id;
private String parentid;
private String name;
}
访问数据接口
@Mapper
public interface Test2Mapper {
List<Test2> selectTreeList();
}
业务实现类
@Service
@Slf4j
public class Test2Service {
@Autowired
private Test2Mapper test2Mapper;
public List<Test2> getTreeList() {
return test2Mapper.selectTreeList();
}
}
控制层类
@Api(value = "TEST2管理", tags = {"TEST2管理"})
@RestController
@Slf4j
@RequestMapping("/test")
public class Test2Controller {
@Autowired
private Test2Service test2Service;
@ApiOperation(value = "树形结构列表")
@GetMapping("/list")
public ResponseEntity listUser() {
TreeNode node = new TreeNode();
List<Test2> treeList = test2Service.getTreeList();
if (treeList.size() > 0) {
for (Test2 test : treeList) {
// 初始化
TreeNode tn = new TreeNode(test.getId(), test.getParentid(), test.getId(), test.getName());
node.add(tn);
}
}
return new ResponseEntity(PublicConstant.SUCCESS_CODE, PublicConstant.SUCCESS_MSG,
node.getChildren());
}
}
接口公共返回实体
@Data
public class ResponseEntity {
//返回编码
private String msgCode;
//返回信息
private String message;
//返回的数据
private Object data;
}
TreeNode工具类
package com.sb.util;
import java.util.ArrayList;
/**
* TreeNode 工具类
*/
public class TreeNode {
private String uuid;
private String parentUuid;
private String tagUuid;
private String poiName;
private ArrayList<TreeNode> children = new ArrayList<TreeNode>();
public TreeNode() {}
/**
* 递归添加节点
*/
public void add(TreeNode node) {
if (node.parentUuid == null || "".equals(node.parentUuid)) {
// 父节点
this.children.add(node);
} else if (node.parentUuid.equals(this.uuid)) {
// 子节点
this.children.add(node);
} else {
for (TreeNode tmp_node : children) {
tmp_node.add(node);
}
}
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getParentUuid() {
return parentUuid;
}
public void setParentUuid(String parentUuid) {
this.parentUuid = parentUuid;
}
public String getTagUuid() {
return tagUuid;
}
public void setTagUuid(String tagUuid) {
this.tagUuid = tagUuid;
}
public String getPoiName() {
return poiName;
}
public void setPoiName(String poiName) {
this.poiName = poiName;
}
public ArrayList<TreeNode> getChildren() {
return children;
}
public void setChildren(ArrayList<TreeNode> children) {
this.children = children;
}
public TreeNode(String uuid, String parentUuid, String tagUuid, String poiName) {
this.uuid = uuid;
this.parentUuid = parentUuid;
this.tagUuid = tagUuid;
this.poiName = poiName;
}
}
接口请求结果
{
"msgCode": "1000",
"message": "操作成功",
"data": [
{
"uuid": "1",
"parentUuid": null,
"tagUuid": "1",
"poiName": "老三",
"children": [
{
"uuid": "2",
"parentUuid": "1",
"tagUuid": "2",
"poiName": "老四",
"children": [
{
"uuid": "3",
"parentUuid": "2",
"tagUuid": "3",
"poiName": "老五",
"children": []
}
]
}
]
}
]
}