Spring Boot +(JPA)-类别层次结构-递归遍历 [英] Spring boot + (JPA) - Category hierarchy - recursively traverse

查看:178
本文介绍了Spring Boot +(JPA)-类别层次结构-递归遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有目录实体-

public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String categoryName;

@ManyToOne
@JoinColumn(name = "parent_id")
private Category parent;

@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<Category> children = new ArrayList<Category>();

@ManyToMany(mappedBy = "categories")
private Set<Product> 

并在表中记录:

id,  category_name,   parent_id
'1', 'HOME',            NULL
'2', 'Category 1',       '1'
'3', 'Category 2',       '1'
'4', 'Sub-Category 1',   '2'
'5', 'Sub-Category 1 2', '2'

控制器中的一些方法(以我为例,但问题是原则性的)

And some methods in the controller (in my case but the questions is principle)

List<Category> categoryList = categoryRepository.findAll();

    for (Category cat : cateList) {
        recursiveTree(cat);
    }



public void recursiveTree(Category cat) {
        System.out.println(cat.getCategoryName());
        if (cat.getChildren().size() > 0) {
            for (Category c : cat.getChildren()) {
                recursiveTree(c);
            }
        }
    }

运行此命令时,在控制台中,我得到-

When i run this, in the console i get -

HOME
Category 1
Sub-Category 1
Sub-Category 1 2
Category 2
Category 1
Sub-Category 1
Sub-Category 1 2
Category 2
Sub-Category 1
Sub-Category 1 2

我如何修改递归,以便可以正确地获得类别和子类别的顺序?我不知道为什么我会得到一些重复的数据

How can i modify the recursion, so i can get the proper order of categories and subcategories? I can't figure out why i get some duplicates data

推荐答案

由于使用 List< Category>从数据库中获取所有类别,因此您获得了重复的数据.categoryList = categoryRepository.findAll();

You get duplicate data because you are fetching all Categories from the database with List<Category> categoryList = categoryRepository.findAll();

此列表包含HOME,Category 1,Category 2,...

This list contains HOME, Category 1, Category 2, ...

由于您针对此列表中的每个项目都在主循环中调用了 recursiveTree 方法,因此您将打印HOME的树(从而将打印其所有子级),因此也将调用类别1的> recursiveTree ,再次打印该类别及其子类别,依此类推.

Since for each item of this list you call the recursiveTree method in your main loop, you will print the tree for HOME (which will thus print all its children), you will also call recursiveTree for Category 1, printing that category and its children again, and so forth.

如果您希望每个类别仅打印一次,则仅查找根类别(HOME和其他可能没有父类别的其他类别),然后为这些类别调用 recursiveTree .例如:

If you want each category printed only once, only look up the root categories (HOME and any others without parent you may have) and call recursiveTree for those. For example:

List<Category> rootCategoryList = categoryRepository.findByParentIsNull();
for (Category cat : rootCategoryList) {
    recursiveTree(cat);
}

这篇关于Spring Boot +(JPA)-类别层次结构-递归遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆