工作中遇到需要后端返回树结构数据给前端
因为layui需要特殊的数据结构
使用jpa
先定义一个layui数据实体
public class LayuiTreeListVo {
private String id;
private String pid;
private String label;
private String levelEk;
private List<LayuiTreeListVo> children=new ArrayList<>();
// todo Setter 与 Getter
//用来嵌套子节点数据
public LayuiTreeListVo addChildrenNode(LayuiTreeListVo layuiTreeListVo){
this.children.add(layuiTreeListVo);
return layuiTreeListVo;
}
}
1、Controller
@RequestMapping(value = "getTree")
public LayuiTreeListVo[] getProductLayoutTreeList() {
LayuiTreeListVo[] arr=new LayuiTreeListVo[1];
arr[0]=rmBaseProductLayoutService.getProductLayoutTreeList();
return arr;
}
2、Service
LayuiTreeListVo getProductLayoutTreeList();
3、此处代码为RmBaseProductLayoutServiceImpl。RmBaseProductLayout为数据库实体类
public LayuiTreeListVo getProductLayoutTreeList() {
//获取所有满足条件的生产环境布局数据
List<RmBaseProductLayout> layouts = rmBaseProductLayoutDao.findByOrgUniqueCdAndDataState(orgId,"1");
//数据转化
List<LayuiTreeListVo> listVos = new ArrayList<>();
for (RmBaseProductLayout productLayout:layouts){
LayuiTreeListVo layuiTreeListVo = getChildrenNode(productLayout);
listVos.add(layuiTreeListVo);
}
//将数据按父级id分组
Map<String, List<LayuiTreeListVo>> group = listVos.stream().collect(Collectors.groupingBy(LayuiTreeListVo::getPid));
List<LayuiTreeListVo> rootList = new ArrayList<>();
for (LayuiTreeListVo treeListVo : listVos) {
//找出所有的子数据
List<LayuiTreeListVo> groupList = group.get(treeListVo.getId());
if (groupList != null) {
treeListVo.setChildren(groupList);
}
//找到首数据
if (treeListVo.getPid().equals("0")) {
rootList.add(treeListVo);
}
}
return rootList.get(0);
}
4、Dao
使用Jpa
public interface IRmBaseProductLayoutDao extends JpaRepository<RmBaseProductLayout,String> {
List<RmBaseProductLayout> findByOrgUniqueCdAndDataState(String orgUniqueCd, String dataState);
}