我能够避免动态查询(使用 Spring Data Specifications)中的计数性能下降,并在几篇文章中指出了基本存储库解决方案。
public class ExtendedRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedRepository<T, ID> {
private EntityManager entityManager;
public ExtendedRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
@Override
public List<T> find(Specification<T> specification, int offset, int limit, Sort sort) {
TypedQuery<T> query = getQuery(specification, sort);
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
}
使用这种方法从 6M 记录数据集中检索 20 个记录切片的查询需要几毫秒。在 SQL 中运行相同的过滤查询。
使用类似的实现Slice<T> find(Specification<T> specification, Pageable pageable)
需要 10 多秒。
类似的实现返回Page<T> find(Specification<T> specification, Pageable pageable)
大约需要 15 秒。