springboot jpa 树对象 递归遍历知道当前第几层

现在时间是周五晚上九点十八分,视线左边手机播放着电影《鬼入侵》,正对着我的就是我的电脑了。刚才玩了几局吃鸡游戏,眼睛花的不想玩了,干脆就敲代码吧,没有女朋友的都和我一样吗?哈哈

最近想把家里的网站升级一下,这个防火布网站主要是把后台重新做一下,昨天写到了数据的显示,今天就写保存了。后台是用vue element写的,感觉这个框架非常好用,有兴趣的可以了解一下,这个tree支持拖拽的。

springboot jpa 树对象 递归遍历知道当前第几层

我的愿望是娶个媳妇帮着设计界面,因为我做出的界面太丑了,有意的可以留言,我还没谈过恋爱呢(用我爸爸的话说还是小雏鸡呢),妳要抓紧联系我呀。

分类对象:Category

package com.dcssn.weian.cms.entity;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 分类
 *
 * @author lihy
 * @version 2018/10/15
 */
@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 名称
     */
    private String name;

    /**
     * 关键词
     */
    private String keywords;

    /**
     * 描述
     */
    private String description;

    /**
     * 层级
     */
    private Integer level;

    /**
     * 排序
     */
    private Integer sequence;

    /**
     * 子类
     */
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "parent_id")
    @OrderBy("sequence asc")
    private List<Category> children = new ArrayList<>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public Integer getSequence() {
        return sequence;
    }

    public void setSequence(Integer sequence) {
        this.sequence = sequence;
    }

    public List<Category> getChildren() {
        return children;
    }

    public void setChildren(List<Category> children) {
        this.children = children;
    }
}

数据库中的内容:

springboot jpa 树对象 递归遍历知道当前第几层

keywords 和 description是我做seo优化用的
CategoryRepository
package com.dcssn.weian.cms.repository;

import com.dcssn.weian.cms.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * 分类
 *
 * @author lihy
 * @version 2018/10/16
 */
public interface CategoryRepository extends JpaRepository<Category, Long> {
    /**
     * 根据层级查找
     *
     * @param level 层级
     * @return java.util.List<com.dcssn.weian.cms.entity.Category>
     * @author lihy
     */
    List<Category> findByLevel(Integer level);

    /**
     * 获取最新的id
     *
     * @return java.lang.Long
     * @author lihy
     */
    @Query(value = "select id from category order by id desc limit 1", nativeQuery = true)
    Long getLatestId();

}
findByLevel(1) 查出数据用于页面展示
[{
	"id": 1,
	"name": "蔬菜",
	"keywords": null,
	"description": null,
	"level": 1,
	"sequence": 0,
	"children": [{
		"id": 3,
		"name": "萝卜",
		"keywords": null,
		"description": null,
		"level": 2,
		"sequence": 0,
		"children": []
	}, {
		"id": 2,
		"name": "白菜",
		"keywords": null,
		"description": null,
		"level": 2,
		"sequence": 1,
		"children": []
	}]
}, {
	"id": 4,
	"name": "水果",
	"keywords": null,
	"description": null,
	"level": 1,
	"sequence": 1,
	"children": [{
		"id": 5,
		"name": "苹果",
		"keywords": null,
		"description": null,
		"level": 2,
		"sequence": 0,
		"children": [{
			"id": 6,
			"name": "青苹果",
			"keywords": null,
			"description": null,
			"level": 3,
			"sequence": 1,
			"children": []
		}, {
			"id": 7,
			"name": "红将军",
			"keywords": null,
			"description": null,
			"level": 3,
			"sequence": 2,
			"children": []
		}]
	}, {
		"id": 8,
		"name": "香蕉",
		"keywords": null,
		"description": null,
		"level": 2,
		"sequence": 1,
		"children": []
	}]
}]

结构就是这样的,当我提交保存的时候也会提交上述格式的数据,返回的数据没有level和sequence信息,所以我们在遍历保存的时候为其赋值。

写个测试类

package com.dcssn.weian;

import com.dcssn.weian.cms.entity.Category;
import com.dcssn.weian.cms.repository.CategoryRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class WeianApplicationTests {

    @Autowired
    CategoryRepository categoryRepository;

    /**
     * 添加数据
     *
     * @author lihy
     */
    @Test
    public void addData() {
        Category category = new Category();
        category.setName("蔬菜");
        Category categoryChild = new Category();
        categoryChild.setName("白菜");
        Category categoryChild2 = new Category();
        categoryChild2.setName("萝卜");
        category.setChildren(new ArrayList<Category>() {{
            add(categoryChild);
            add(categoryChild2);
        }});
        categoryRepository.save(category);
    }

    /**
     * 读取数据
     *
     * @author lihy
     */
    @Test
    public void readData() {
        List<Category> categoryList = categoryRepository.findByLevel(1);
        for (int i = 0; i < categoryList.size(); i++) {
            recursion(categoryList.get(i), 1, i);
        }
    }

    /**
     * 递归
     *
     * @param category 分类
     * @param level    层级
     * @param index    同级排序
     * @author lihy
     */
    private void recursion(Category category, int level, int index) {
        System.out.printf("%" + level * 2 + "s\n", category.getName());
        // TODO: 设置 category的level和sequence 并保存
        Category categoryTemp;
        for (int i = 0; i < category.getChildren().size(); i++) {
            categoryTemp = category.getChildren().get(i);
            recursion(categoryTemp, level + 1, i);
        }
    }

}

运行结果

springboot jpa 树对象 递归遍历知道当前第几层

qq 529568252