【发布时间】:2021-03-29 19:43:37
【问题描述】:
@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;
}
是否可以创建循环遍历产品的所有类别父级的递归查询?
假设我在 For Woman 类别中,它将遍历所有类别的父母,如果其中一个与 For Woman 匹配,它将返回它的产品..
基本上,我想要的是这样的(查询它)..
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();
}
}
【问题讨论】:
-
也许您可以为递归查询编写一个 mysql CTE 视图并将实体映射到该视图
-
你能在代码之前描述问题吗?
-
每个产品都有自己的类别...类别可以属于另一个类别(父类别)..所以假设我想从类别中查找产品女性..这不是问题...但是我想选择所有类别父母包括女性类别的产品..
标签: mysql spring spring-boot spring-data-jpa