【问题标题】:Sort On Child List total count using JpaRepository Spring-data-jpa使用 JpaRepository Spring-data-jpa 对子列表总数进行排序
【发布时间】:2018-10-30 12:39:18
【问题描述】:

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

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

this link 和其他堆栈溢出的答案中,我发现我可以使用Paging Request like 进行排序和分页

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

我的问题是我在模型中有一个self join 父子关系,我需要根据子节点的数量对父节点进行排序,如下所示。

这里的Number of SubCategoriescategoriesByCategoryId 的大小。我需要在id 的位置传递PageRequest 以根据子列表的大小进行排序。

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

【问题讨论】:

    标签: java sorting spring-boot spring-data-jpa repository


    【解决方案1】:

    经过this answer之后,我能够通过使用自定义查询来实现需求,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 查询。

    【讨论】:

      猜你喜欢
      • 2016-01-23
      • 2014-06-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 2023-03-04
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多