对于菜单,以及省市区联动这种数据, 要从数据库取出来传给前端,然后前端通过ztree之类的框架进行展示,那么这里我写了一个将数据库中的数据,转成dto的树状结构的工具方法
这里用了lombok框架,所以需要导lombok依赖
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.20version>
dependency>
这样只需要一个@Data注解就可以省去getter和setter了
idea还需要加一个插件LomBok plugin
package com.zgd.demo.entity;
import lombok.Data;
/**
* 菜单
* @author zgd
*/
@Data
public class Menu {
private Integer id;
private String name;
private Integer parentId;
private Integer level;
public Menu(Integer id, String name, Integer parentId, Integer level) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.level = level;
}
}
package com.zgd.demo.dto;
import lombok.Data;
import java.util.List;
/**
* menu的dto类
* @author zgd
*/
@Data
public class MenuDto {
private Integer id;
private String name;
private Integer parentId;
private Integer level;
private List children;
}
package com.zgd.demo.util.bean;
import com.zgd.demo.dto.MenuDto;
import com.zgd.demo.dto.UserDto;
import com.zgd.demo.entity.Menu;
import com.zgd.demo.entity.User;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* 将数据库查出来的list数据抓成树状结构
* @author zgd
*/
public class List2TreeUtil {
/**
* 根级父ID
*/
private static final Integer ROOT_PARENT_ID = 0;
/**
* 将普通的entity的集合转成存在树状结构的集合
* @param list
* @return
*/
public static List getDtoTreeList(List
package com.zgd.demo;
import com.google.gson.Gson;
import com.zgd.demo.entity.Menu;
import com.zgd.demo.util.bean.List2TreeUtil;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import java.util.ArrayList;
import java.util.List;
/**
* 运行demo
* @author zgd
*/
public class DemoTest {
public static void main(String[] args) {
Gson gson = new Gson();
List list = new ArrayList<>();
list.add(new Menu(1,"顶级目录",0,1));
list.add(new Menu(2,"二级目录-a",1,2));
list.add(new Menu(3,"二级目录-b",1,2));
list.add(new Menu(4,"三级目录-a-a",2,3));
list.add(new Menu(5,"三级目录-a-b",2,3));
list.add(new Menu(6,"三级目录-a-c",2,3));
list.add(new Menu(7,"三级目录-b-a",3,3));
System.out.println(gson.toJson(List2TreeUtil.getDtoTreeList(list)));
}
}