黑馬程序員Java項(xiàng)目企業(yè)級(jí)微服務(wù)實(shí)戰(zhàn)《學(xué)成在線》,基于SpringCloud、

在P31-P33中課程分類查詢中,老師提供了SQL的分類方法,結(jié)合其他評(píng)論區(qū)的遞歸調(diào)用,我發(fā)覺需多次查詢數(shù)據(jù)庫(kù),并且響應(yīng)時(shí)間較長(zhǎng),于是作出一下修改:
1.只查詢一次數(shù)據(jù)庫(kù),將結(jié)果放入Map中,key是父節(jié)點(diǎn),value是CourseCategory集合,該Map將父節(jié)點(diǎn)是同一節(jié)點(diǎn)的數(shù)據(jù)收集成一個(gè)list,后續(xù)通過map可以快速取出。
2.遞歸調(diào)用,將最終樹形結(jié)構(gòu)存入內(nèi)存中,后續(xù)不再查數(shù)據(jù)庫(kù)。
3.實(shí)現(xiàn)了InitializingBean,重寫afterPropertiesSet,在項(xiàng)目啟動(dòng)時(shí)就執(zhí)行該操作。
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService, InitializingBean {
??private static Map<String, List<CourseCategory>> map = new HashMap<>();
??private static List<CourseCategoryTreeDto> treeDtoList;
??private static final String ROOT_ID = "1";
??@Autowired
??private CourseCategoryMapper courseCategoryMapper;
??@Override
??public List<CourseCategoryTreeDto> findTreeNodes() {
????if (Objects.isNull(treeDtoList)) {
??????List<CourseCategory> courseCategoryList = courseCategoryMapper.selectList(null);
??????courseCategoryList.forEach(courseCategory -> {
????????String parentid = courseCategory.getParentid();
????????List<CourseCategory> courseCategories = map.get(parentid);
????????if (Objects.isNull(courseCategories)) {
??????????courseCategories = new ArrayList<>();
????????}
????????courseCategories.add(courseCategory);
????????map.put(parentid, courseCategories);
??????});
??????treeDtoList = map.get(ROOT_ID).stream().map(this::buildTree).collect(Collectors.toList());
??????map = null;
????}
????return treeDtoList;
??}
??/**
???* 遞歸查詢
???*?
???* @param courseCategory
???* @return
???*/
??private CourseCategoryTreeDto buildTree(CourseCategory courseCategory) {
????CourseCategoryTreeDto dto = new CourseCategoryTreeDto();
????BeanUtils.copyProperties(courseCategory, dto);
????List<CourseCategory> children = map.get(courseCategory.getId());
????if (!CollectionUtils.isEmpty(children)) {
??????List<CourseCategoryTreeDto> collectTreeNodes =
????????children.stream().map(this::buildTree).collect(Collectors.toList());
??????dto.setChildrenTreeNodes(collectTreeNodes);
????}
????return dto;
??}
??@Override
??public void afterPropertiesSet() throws Exception {
????findTreeNodes();
????map = null;
??}
}