[英]Pagination in SeedStack Repositories
在我的Java项目中,使用SeedStack,我有一些查询来使用类似的规范从聚集中检索数据:
更新:已修复代码示例,以显示正确的返回类型方法
public interface ProductRepository extends Repository<Product, ProductId> {
default Stream<Product> discontinuedProducts() {
return get(getSpecificationBuilder().of(Product.class)
.property("discontinued").equalTo(true)
.build()
);
}
}
为了避免潜在的内存不足错误,我想使用分页来拆分某些存储库查询中检索到的数据。
此外,我想使用与String Data Repositories中存在的分页功能非常相似的功能。 我想保留结果的某些元素(而不是全部),并通过“页面”对其进行处理,而不必将所有数据结果都保留在Collection中。
在Spring中进行分页和排序: https : //docs.spring.io/spring-data/rest/docs/2.0.0.M1/reference/html/paging-chapter.html
但是,我阅读了SeedStack文档,但没有找到此功能。
SeedStack中的存储库: http ://seedstack.org/docs/business/repositories/
因此,我想知道使用SeedStack分页查询结果的最佳方法是什么。
SeedStack为助手提供了几种不同的分页方法,但是遗憾的是在这方面缺少文档。
在进行详细介绍之前,请注意,您的discontinuedProducts()
方法应该返回Stream<Product>
而不是List<Product>
因为存储库的get
方法将返回流。
使用SeedStack进行分页的主要方法是使用Paginator DSL ,该DSL插入存储库顶部以提供分页。
示例1(直接对流进行分页):
public class SomeResource {
@Inject
private Paginator paginator;
@Inject
private ProductRepository productRepository;
@Inject
private FluentAssembler fluentAssembler;
public void someMethod() {
Page<Product> page = paginator.paginate(productRepository.discontinuedProducts())
.byPage(1)
.ofSize(10)
.all();
}
}
示例2(使用规范对存储库进行分页):
public class SomeResource {
@Inject
private Paginator paginator;
@Inject
private ProductRepository productRepository;
@Inject
private SpecificationBuilder specificationBuilder;
public void someMethod() {
Page<Product> page = paginator.paginate(productRepository)
.byPage(1)
.ofSize(10)
.matching(specificationBuilder.of(Product.class)
.property("discontinued").equalTo(true)
.build());
}
}
示例3(在混合中添加DTO映射):
public class SomeResource {
@Inject
private Paginator paginator;
@Inject
private ProductRepository productRepository;
@Inject
private SpecificationBuilder specificationBuilder;
@Inject
private FluentAssembler fluentAssembler;
public void someMethod() {
Page<ProductDto> page = fluentAssembler.assemble(
paginator.paginate(productRepository)
.byPage(1)
.ofSize(10)
.matching(specificationBuilder.of(Product.class)
.property("discontinued").equalTo(true)
.build()))
.toPageOf(ProductDto.class)
}
}
在最后一个示例中,SeedStack将:
请注意,如果您要一遍又一遍地重用同一规范,将其转换为类(如
DiscontinuedProductSpec
)或在存储库中创建一个方法来构建它(如buildDiscontinuedProductSpec()
)可能会很有用。
还有其他几种组合这些工具的方法,请检查Paginator , FluentAssembler和Repository的Javadoc。 您还可以查看分页集成测试,以获取更多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.