@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;
}}
1条答案
按热度按时间cx6n0qe31#
类别
公共类类别{
储存库
服务类别
}