英文:
Spring PagingAndSortingRepository delete entry during processing
问题
使用Spring的PagingAndSortingRepository来对数据库条目进行分页。在处理过程中,我需要删除一些条目。
当我调用仓库进行删除操作时,条目被删除,之后的问题出现在下一个可分页对象中。我无法从下一个可分页对象(pageRequest.next())中获取到预期数量的元素。
是否有办法在进行分页迭代的同时并行执行CRUD操作。
代码的部分片段如下:
while (!onePage.isEmpty()) {
while (pageIterator.hasNext()) {
Object nextElement = pageIterator.next();
if (!falseCondition) {
log.info("发送带有ID {} 的消息", nextElement.getId());
repository.deleteById(nextElement.getId());
} else {
log.info("连接丢失");
return;
}
}
pageRequest = pageRequest.next();
onePage = repository.findAll(pageRequest);
pageIterator = onePage.iterator();
}
非常感谢。
英文:
Im using spring PagingAndSortingRepository to do pagination of database entries.
During processing i need to delete some entries..
when i call the repository to delete, the entry is deleted, after that the problem is with the next pageable. i'm not getting the size number of elements from the next Pageable (pageRequest.next();).
Is there any way to iterate with pagination and perform in parallel crud operation.
Part of the code
while (!onePage.isEmpty()) {
while (pageIterator.hasNext()) {
Object nextElement = pageIterator.next();
if (!falseCondition) {
log.info("sending message with Id {}", nextElement.getId());
repository.deleteById(nextElement.getId());
} else {
log.info("Lost connection");
return;
}
}
pageRequest = pageRequest.next();
onePage = repository.findAll(pageRequest);
pageIterator = onePage.iterator();
}
Many thanks.
答案1
得分: 2
就像 @ruba 在示例中指出的那样,这不是一个 Hibernate 的问题。即使您直接使用 JDBC API,您也必须处理这种情况。我可以为您提供一个解决方案
- 您可以实现自己的自定义
spring-data-jpa
仓库方法,其中服务传递pageRequest
,但您将其转换为offset
和limit
。因此,不要调用pageRequest.next()
,而是执行以下操作,它考虑了已在当前页面中删除的项目。
long nextPageNumber = pageRequest.getPageNumber() + 1;
long nextOffset = nextPageNumber * pageRequest.getPageSize()
- itemsDeletedInCurrentPage;
long limit = pageRequest.getPageSize();
List<Item> itemsInNextPage = em.createQuery(query)
.setFirstResult(offset)
.setMaxResults(limit)
.getResultList();
英文:
Like @ruba pointed out in the example, it is not a hibernate issue. Even if you using jdbc API directly you will have to handle the situation. I can propose you a solution
- You can implement your custom
spring-data-jpa
repository method where the service pass thepageRequest
but you translate it tooffset
andlimit
. So instead of callingpageRequest.next()
you do the following which takes into account of the items deleted.
long nextPageNumber = pageRequest.getPageNumber() + 1;
long nextOffset = nextPageNumber * pageRequest.getPageSize()
- itemsDeletedInCurrentPage;
long limit = pageRequest.getPageSize();
List<Item> itemsInNextPage = em.createQuery(query)
.setFirstResult(offset)
.setMaxResults(limit)
.getResultList();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论