使用 JpaRepository Spring-data-jpa 对子列表总数进行排序

Ana*_*nas 2 java sorting repository spring-data-jpa spring-boot

我需要对实体进行分页和排序。

@Entity
@Table(name = "CATEGORY", catalog = "")
public class CategoryEntity {
 private CategoryEntity categoryByParentCategoryId;
 private Set<CategoryEntity> categoriesByCategoryId;


@ManyToOne(fetch = FetchType.LAZY,optional = false, cascade = CascadeType.PERSIST)
@JoinColumn(name = "PARENT_CATEGORY_ID", referencedColumnName = "CATEGORY_ID")
public CategoryEntity getCategoryByParentCategoryId() {
    return categoryByParentCategoryId;
}

public void setCategoryByParentCategoryId(CategoryEntity categoryByParentCategoryId) {
    this.categoryByParentCategoryId = categoryByParentCategoryId;
}

@OneToMany(mappedBy = "categoryByParentCategoryId", cascade = CascadeType.PERSIST)
public Set<CategoryEntity> getCategoriesByCategoryId() {
    return categoriesByCategoryId;
}

public void setCategoriesByCategoryId(Set<CategoryEntity> categoriesByCategoryId) {
    this.categoriesByCategoryId = categoriesByCategoryId;
}
Run Code Online (Sandbox Code Playgroud)

这个链接和其他堆栈溢出的答案,我发现我可以使用排序和使用分页Paging Request

Pageable size = new PageRequest(page, paginationDTO.getSize(),Sort.Direction.ASC, "id");
Run Code Online (Sandbox Code Playgroud)

我的问题是我有一个self join父子关系,如上图所示,我需要根据子项的计数对父项进行排序,如下所示。

类别实体的数据表

这里Number of SubCategories是 的大小categoriesByCategoryId。我需要在PageRequestin 的地方传递什么id来根据子列表的大小进行排序。

附注。该模型有更多的字段,但为了简短的问题,我只发布了相关的字段

Ana*_*nas 5

通过这个答案后,我能够通过使用自定义查询来实现需求,JPARepository 中的方法看起来像

@Query(
        value = "select c from CategoryEntity c " +
                " WHERE LOWER(c.categoryNameEn) LIKE LOWER(CONCAT('%',?2, '%')) AND activeInd = ?1 " +
                "AND c.categoryByParentCategoryId is null" +
                " Order By c.categoriesByCategoryId.size desc",
        countQuery = "select count(c) from CategoryEntity c " +
                " WHERE LOWER(c.categoryNameEn) LIKE LOWER(CONCAT('%',?2, '%')) AND activeInd = ?1" +
                " AND c.categoryByParentCategoryId is null"
)
Page<CategoryEntity> findAllActiveCategoriesByCategoriesByCategoryIdCountDesc(String activeInd, String categoryNameEn, Pageable pageable);
Run Code Online (Sandbox Code Playgroud)

分页详细信息需要 Count 查询。