由于QueryDslPredicateExecutor 不支持将Slice 作为findAll(Predicate, Pageable) 的返回值返回,所以计数查询 似乎是不可避免的。但是您可以定义一个新的基本存储库接口并以不发出分页计数查询的方式实现findAll 方法。对于初学者,您应该定义一个接口,该接口将用作所有其他 Repositories 的基本接口:
/**
* Interface for adding one method to all repositories.
*
* <p>The main motivation of this interface is to provide a way
* to paginate list of items without issuing a count query
* beforehand. Basically we're going to get one element more
* than requested and form a {@link Page} object out of it.</p>
*/
@NoRepositoryBean
public interface SliceableRepository<T, ID extends Serializable>
extends JpaRepository<T, ID>,
QueryDslPredicateExecutor<T> {
Page<T> findAll(Predicate predicate, Pageable pageable);
}
然后,像这样实现这个接口:
public class SliceableRepositoryImpl<T, ID extends Serializable>
extends QueryDslJpaRepository<T, ID>
implements SliceableRepository<T, ID> {
private static final EntityPathResolver DEFAULT_ENTITY_PATH_RESOLVER = SimpleEntityPathResolver.INSTANCE;
private final EntityPath<T> path;
private final PathBuilder<T> builder;
private final Querydsl querydsl;
public SliceableRepositoryImpl(JpaEntityInformation<T, ID> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
path = DEFAULT_ENTITY_PATH_RESOLVER.createPath(entityInformation.getJavaType());
this.builder = new PathBuilder<>(path.getType(), path.getMetadata());
this.querydsl = new Querydsl(entityManager, builder);
}
@Override
public Page<T> findAll(Predicate predicate, Pageable pageable) {
int oneMore = pageable.getPageSize() + 1;
JPQLQuery query = createQuery(predicate)
.offset(pageable.getOffset())
.limit(oneMore);
Sort sort = pageable.getSort();
query = querydsl.applySorting(sort, query);
List<T> entities = query.list(path);
int size = entities.size();
if (size > pageable.getPageSize())
entities.remove(size - 1);
return new PageImpl<>(entities, pageable, pageable.getOffset() + size);
}
}
基本上,此实现将获取比请求大小多一个的元素,并将结果用于构造Page。然后你应该告诉 Spring Data 使用这个实现作为存储库基类:
@EnableJpaRepositories(repositoryBaseClass = SliceableRepositoryImpl.class)
最后将SliceableRepository 扩展为您的基本接口:
public SomeRepository extends SliceableRepository<Some, SomeID> {}