java后台通过访问数据库得到数据来生成树是很常用的的方法
这个有很多种方法可以实现 我这里就说对我比较印象深刻的两种方法
一种是自己写的 后台拼接一点点的数据就要9秒之多
另一种是我借鉴我老大写得 后台拼接只要3面左右 (两种方法是在同样的数据和同样的环境中比较的)
为什么说这两种方法会对我影响比较大呢
因为这两种方法代表了两种实现思想
首先是我这个比较low的 我的思想就是先获取到根节点 然后通过根节点的 id 来查询所有 parentId = 根id 的数据
这样通过递归来实现 非常的慢 而且代码量非常的多
我也不怕丢人 贴出来给大家看看
/**
* 递归树 java层数据
* @param mapper
* @param parentId
* @return
*/
public static List<TreeWyRoom> infiniteTree( WyRoomMapper mapper,Integer parentId,Integer xqId){
List<TreeWyRoom> treeRooms = new ArrayList<>();
WyRoomExample example = new WyRoomExample();
WyRoomExample.Criteria ccc=example.createCriteria();
ccc.andParentIdEqualTo(parentId);
ccc.andXqIdEqualTo(xqId);
List<WyRoom> wyRooms = mapper.selectByExample(example);
Comparator<WyRoom> comparator = new Comparator<WyRoom>(){
@Override
public int compare(WyRoom o1, WyRoom o2) {
return o1.getCode().compareTo(o2.getCode());
}
};
Collections.sort(wyRooms,comparator);
for( WyRoom wyRoom : wyRooms ){
TreeWyRoom treeWyRoom = new TreeWyRoom();
treeWyRoom.setId(wyRoom.getId());
treeWyRoom.setParentId(wyRoom.getParentId());
treeWyRoom.setLevel(wyRoom.getLevel());
treeWyRoom.setPcId(wyRoom.getPcId());
treeWyRoom.setXqId(wyRoom.getXqId());
treeWyRoom.setCode(wyRoom.getCode());
treeWyRoom.setAlias(wyRoom.getAlias());
treeWyRoom.setType(wyRoom.getType());
treeWyRoom.setCreateDate(wyRoom.getCreateDate());
treeWyRoom.setCreator(wyRoom.getCreator());
treeWyRoom.setLastModDate(wyRoom.getLastModDate());
treeWyRoom.setLastModifier(wyRoom.getLastModifier());
treeRooms.add(treeWyRoom);
}
for(TreeWyRoom treeRoom : treeRooms){
if(treeRoom.getLevel()==2){
treeRoom.setPlzj(true);
}
treeRoom.setChildren(infiniteTree(mapper,treeRoom.getId(),xqId));
}
return treeRooms;
}
/**
* 把递归树拼接成JSON
* @param treeRoom
* @param o
* @return
*/
public