Spring Data JPA 循环槽父

时间:2020-12-19 11:07:09

标签: mysql spring spring-boot spring-data-jpa

    @Entity
    public class Product {
        @Id
        @Column(unique = true)
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
        private String title;
        @OneToOne
        private Brand brand;
        @OneToOne(fetch = FetchType.EAGER)
        @OnDelete(action = OnDeleteAction.CASCADE)
        private Category category;
}
    
    @Entity
    public class Category {
        @Id
        @Column(unique = true)
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
        @NotBlank(message = "Please enter category name!")
        @Length(max = 50, message = "Maximum size exceeded!")
        private String name;
        @OneToOne
        private Category parent;
}

是否可以创建循环查询产品的所有类别父级的递归查询?

假设 im 在 For Woman 类别中,它将循环遍历所有类别的父类,如果其中一个与 For Woman 匹配,它将返回它的产品..

enter image description here

基本上,我想要的是这样的(查询它)..

  List<ProductOption> productOptions = new ArrayList<>();

        Category mainCategory = categoryRepository.findById(id);

            for(Category category : categoryRepository.findAll()){
                Category cat = category;
                while(cat!=null){
                    if(cat==mainCategory){
                        productOptions.addAll(productOptionRepository.findAllByProduct_CategoryId(category.getId()));
                    }
                    cat=cat.getParent();
                }
             }

0 个答案:

没有答案