1 回答
TA贡献1799条经验 获得超8个赞
这是根据使用 Spring Data JpaRepository 按计数排序的解决方案。
在我的实验中,我尝试将 Repository 定义如下,但存在问题;因为我们正在定义PersonRepository基于 addressCount 进行排序的查询,spring 数据会查看 Person。
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(
value = "select p from Person p join p.addresses ad group by p",
countQuery = "select count(p) from Person p"
)
Page <Person> findAllWithAddressCount(Pageable pageable);
}
因此,作为一种解决方法,我尝试将排序逻辑转移到查询定义本身中,最终得到了两个版本的 ASC 和 DESC 模式:
@Repository
public interface PersonRepository extends JpaRepository <Person, Long> {
@Query(
value = "select p from Person p join p.addresses ad group by p Order By addressCount asc",
countQuery = "select count(p) from Person p"
)
Page<Person> findAllOrderByAddressCountAsc(Pageable pageable);
@Query(
value = "select p from Person p join p.addresses ad group by p Order By addressCount desc",
countQuery = "select count(p) from Person p"
)
Page<Person> findAllOrderByAddressCountDesc(Pageable pageable);
}
希望这会有所帮助。
添加回答
举报