【发布时间】:2021-08-18 23:38:04
【问题描述】:
Java 分页有问题。在我的代码中,我更新了我的数据库(MongoDB)中的一些记录,但我正在尝试使用分页,因为该过程花费了太多时间。所以,基本上我正在使用这样的东西:
int npages = 10;
int count = (query for count records);
int lote = count / npages;
for (int i = 0; i < npages + 1; i++) {
Pageable page = PageRequest.of(i, lote);
List < Example > example;
example = exampleRepository
.findByExample(parameter, page);
if (null != example) {
log.info("For i: " + i + " size: " + example.size());
}
new Thread(() -> {
try {
log.info("Start thread");
process(example);
} catch (Exception e) {
log.error("Error processing: " + e.getMessage());
}
}).start();
}
所以,我决定有 10 页,所以我对所有记录进行计数(那个查询没问题,我检查了数据库,结果是正确的),然后我使用 for,我在那里创建页面根据它的大小,我使用 Pageable 页面进行查询。
问题是有时最后一页和上一页都是空的。例如,如果我有 1235 条记录,我将有 10 页,9 页有 123,最后一页有 5 个。但有时我有 8 个有 123 的记录,一个可能有 100 或类似的东西,还有一个有 0。
我之所以评论有时是因为两个原因,我已经在另外两个过程中使用了这个分页,在这两个过程中都可以正常工作。因为,在这个过程中,有时页面是完整的(当我有类似 100/10 = 10 的东西时不是这样。不,最后一页的大小不等也可以正常工作,有时,但并非总是如此)。 所以,我无法理解发生了什么。
如果我再次运行该过程,它将获取并处理丢失的记录。我在第一次执行时需要它。
例如,这是其中一次执行,我记录了计数和手数:
INFO - [http-nio-8080-exec-3] - Count: 954 Lote: 95
INFO - [http-nio-8080-exec-3] - For i: 0 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 1 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 2 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 3 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 4 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 5 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 6 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 7 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 8 sumAmount.size(): 95
INFO - [http-nio-8080-exec-3] - For i: 9 sumAmount.size(): 5
INFO - [http-nio-8080-exec-3] - For i: 10 sumAmount.size(): 0
所以 95*9 = 855 + 5 = 860。缺少 94 条记录。我很确定这个数字。在这次尝试中,我使用了测试环境数据库,但我也尝试使用本地数据。有 52 条记录,有些处决工作得很好,但我记得我有一个有 5 批 5,其余的是空的。
查询:
计数:
@Aggregation(pipeline = { "{ $match : { 'example.date': { $lt: ?0}, 'example.state': {$elemMatch: {name: 'Aceptado' }}} }", "{ $group: {_id : null, count : {$sum : 1}}}"})
int count(String date);
数据:
List<RewardAccepted> findByExampleStateNameAndExampleDateLessThan(String exampleStateName ('Aceptado' of course), String date, Pageable pageable);
(两者的日期相同)
【问题讨论】:
标签: java spring mongodb spring-boot pagination