繁体   English   中英

使用JpaRepository Spring-data-jpa在子列表上排序总数

[英]Sort On Child List total count using JpaRepository Spring-data-jpa

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

@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;
}

从此链接和其他堆栈溢出答案中,我发现可以使用Paging Request使用排序和分页,例如

Pageable size = new PageRequest(page, paginationDTO.getSize(),Sort.Direction.ASC, "id");

我的问题是我有一个上面模型中所示的self join父子关系,我需要根据子计数对父排序,如下所示。

类别实体的数据表

在这里Number of SubCategories categoriesByCategoryIdNumber of SubCategories的大小。 我需要在id中的PageRequest中传递什么,以便根据子列表的大小进行排序。

PS。 该模型有更多字段,但为简短起见,我只发布了相关字段

经过这个答案之后,我能够通过使用自定义查询来达到要求,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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM