在日常开发中会有多级数据联动,将数据使用递归思想组织成树形结构,进行前后端数据交互。模拟一张部门表,实现省、市和县树形结构。
一 创建数据库表模型
CREATE TABLE `sys_depart` (
`id` VARCHAR(32) NOT NULL COMMENT '部门主键id',
`name` VARCHAR(32) DEFAULT NULL COMMENT '部门名称',
`parent_id` VARCHAR(32) DEFAULT NULL COMMENT '父级部门id',
`parent_name` VARCHAR(32) DEFAULT NULL COMMENT '父级部门名称',
PRIMARY KEY (`id`)
) ENGINE=INNODB;
二 创建depart表的基础代码
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_depart")
public class Depart {
@TableId
private String id;
private String name;
private String parentId;
private String parentName;
@TableField(exist = false)
private List<Depart> departList = new ArrayList<>();
}
@Mapper
public interface DepartMapper extends BaseMapper<Depart> {
}
public interface IDepartService extends IService<Depart> {
}
@Service
public class DepartServiceImpl extends ServiceImpl<DepartMapper, Depart>
implements IDepartService {
}
三 组装部门树结构
@SpringBootTest
@RunWith(SpringRunner.class)
public class DepartTest {
@Autowired
private IDepartService departService;
@Test
public void test1() {
List<Depart> list = departService.list();
List<Depart> departTree = sysDepartTree(list);
String result = JSONObject.toJSONString(departTree);
System.out.println("result is: " + result);
}
public List<Depart> sysDepartTree(List<Depart> list) {
List<Depart> departTree =
list.stream().filter(depart -> depart.getParentId() == null)
.collect(Collectors.toList());
departTree.forEach(depart -> recursion(depart, list));
return departTree;
}
public void recursion(Depart parentDepart, List<Depart> departList) {
List<Depart> childrenDapart = getChildrenNode(parentDepart, departList);
if (childrenDapart.size() > 0) {
childrenDapart.forEach(depart -> recursion(depart, departList));
}
}
public List<Depart> getChildrenNode(Depart parentDepart, List<Depart> departList) {
departList.forEach(depart -> {
if (parentDepart.getId().equals(depart.getParentId())) {
parentDepart.getDepartList().add(depart);
}
});
return parentDepart.getDepartList();
}
}