一、商品类型表
二、java实现查询出商品类别的所有子节点
1.1 递归(效率太低)
/**
* 通过递归获取分类树(数据量大时,效率低)
*
* @param pid
* @return
*/
public List<ProductType> getAllProductTypesByRes(Long id) {
List<ProductType> children = mapper.getChildren(id);//通过商品类型id查询商品类型的子节点
for (ProductType productType : children) {
List<ProductType> afterChildren = getAllProductTypesByRes(productType.getId());//递归查孙节点
productType.setChildren(afterChildren);
}
return children;
}
前台响应时间:结果:3.48s响应出来我们都可以和几杯咖啡了。
1.2 通过循环获取分类树
private List<ProductType> getAllTreeByLoop(Long pid) {
List<ProductType> orginals = null;
if (pid == 0) {
orginals = mapper.getAll();
} else {
orginals = mapper.getTypes(pid);
}
if (null == orginals)
return null;
Map<Long, ProductType> dtoMap = new HashMap<Long, ProductType>();
for (ProductType node : orginals) {
dtoMap.put(node.getId(), node);
}
List<ProductType> resultList = new ArrayList<ProductType>();
for (Map.Entry<Long, ProductType> entry : dtoMap.entrySet()) {
ProductType node = entry.getValue();
if (node.getPid() == pid) {
// 如果是顶层节点,直接添加到结果集合中
resultList.add(node);
} else {
// 如果不是顶层节点,找的起父节点,然后添加到父节点的子节点中
if (dtoMap.get(node.getPid()) != null) {
dtoMap.get(node.getPid()).addChild(node);
}
}
}
return resultList;
}
三、优化
无论是使用那种方法,都是会去数据库查询,又因为商品类型不是经常改变,我们可以尝试静态化到远程,比如使用七牛云云存储或者阿里云,然后在我们jsp页面中加载七牛云提供给我们的json数据。