我有一个实体,其属性"father"是对其父亲的引用。(就像在数据库中一样)现在我需要在视图中创建一个树,我需要递归地携带子节点。我已经做了下面的方法,但我加倍了孩子。而不是进一步的(最佳)正确的方式来完成这个过程。有人能帮帮我吗?谢谢你。
@Transactional(readOnly = true)
public Page<CategoriaDTO> findAll(Pageable pageable) {
log.debug("Request to get all Categorias");
Page<Categoria> result = categoriaRepository.findByPadreIsNull(pageable);
List<CategoriaDTO> categoriaDtos = new ArrayList<>();
for (Categoria categoriaAux : result) {
CategoriaDTO categoriaDto = categoriaMapper.categoriaToCategoriaDTO(categoriaAux);
categoriaDto.setHijos(categoriaMapper.categoriasToCategoriaDTOs(categoriaRepository.findByPadre(categoriaAux)));
hijos(categoriaDto.getHijos(),categoriaDto.getId());
categoriaDtos.add(categoriaDto);
}
return new PageImpl<CategoriaDTO>(categoriaDtos);
}
private void hijos(List<CategoriaDTO> hijos,Long padreId){
Categoria categoriaPadre = categoriaRepository.findOne(padreId);
if(! CollectionUtils.isEmpty(hijos)){
for (CategoriaDTO hijo : hijos) {
hijo.setHijos(categoriaMapper.categoriasToCategoriaDTOs(categoriaRepository.findByPadre(categoriaPadre)));
hijos(hijo.getHijos(),hijo.getId());
}
}
}
据我所知,在您的实体中,您有对同一实体的引用。所以你可以从叶子开始,然后往上走。递归地调用该函数,直到Entity的父节点为空(这意味着您到达了根节点)。您还可以将实体添加到列表中。
LinkedList<Category> list = new LinkedList<>();
public void getChildren(Category category) {
list.add(category);
if(category.getParent() == null)
return;
getChildren(category.getParent());
}
这只是一个例子,张贴你的实体的更多细节