问题背景:
上一篇博客(JPA排序中的join排序及case when的使用)中有提到一个场景:对象A中包含了Set<B> objBs这样一个成员,要求查询A时按A中包含的B数量排序,当时的解决方案是count一下B,然后order by这个count,详见上一篇博客。
上面的方法确实解决了排序的问题,但是经过多次测试发现,当按照objBs排序、查询第一页时,数据正确,但是total不对,实际上我有11条数据,但是total返回的是17。
数据库中:
问题定位:
代码调用的是JPA的默认实现SimpleJpaRepository中的
public Page<T> findAll(Specification<T> spec, Pageable pageable) {
TypedQuery<T> query = getQuery(spec, pageable);
return pageable == null ? new PageImpl<T>(query.getResultList())
: readPage(query, getDomainClass(), pageable, spec);
}
过程可以自己看源码,这里列出出现问题的核心代码:
private static Long executeCountQuery(TypedQuery<Long> query) {
Assert.notNull