Spring Boot:如何在表中设置父子关系(层次或递归)

92vpleto  于 2023-01-13  发布在  Spring
关注(0)|答案(1)|浏览(199)

如何在JPA spring Boot /spring mvc中使用parent id设置菜单、子菜单的表中的父子关系(层次或递归)?以及如何使用CrudRepository/JpaRepository创建层次或递归json?
图片中的表格结构

cx6n0qe3

cx6n0qe31#

类别

@Entity

公共类类别{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long categoryId;

@Column(nullable = false)
public String name;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_category_id")
@JsonIgnore
public Category parentCategory;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "root_category_id")
@JsonIgnore
public Category rootCategory;

@Transient
public List<Category> childrens = new ArrayList<Category>();}

储存库

@Repository
public interface CategoryRepository extends JpaRepository<Category, Long> {
    
@Query("SELECT category FROM Category category "
        + " WHERE category.parentCategory.categoryId IS NULL")
public List<Category> findAllRoots();

@Query("SELECT category FROM Category category"
        + " WHERE category.rootCategory.categoryId IN :rootIds ")
public List<Category> findAllSubCategoriesInRoot(@Param("rootIds") List<Long> rootIds);}

服务类别

@Service
public class CategoryService {

@Autowired
public CategoryRepository categoryRepository;

@GetMapping("/categories")
@Transactional(readOnly = true)
public List<Category> getCategories() {
    List<Category> rootCategories = categoryRepository.findAllRoots(); // first db call

    // Now Find all the subcategories
    List<Long> rootCategoryIds = rootCategories.stream().map(Category::getCategoryId).collect(Collectors.toList());
    List<Category> subCategories = categoryRepository.findAllSubCategoriesInRoot(rootCategoryIds); // second db call

    subCategories.forEach(subCategory -> {
        subCategory.getParentCategory().getChildrens().add(subCategory); // no further db call, because everyone inside the root is in the persistence context.
    });

    return rootCategories;
}}

}

相关问题