简体   繁体   中英

Spring JPA Transactional commit during process with Pessimistic lock

I need to perform the batch operation with a Pessimistic lock so that no other can read or write this row during this operation. But I want to increment the page number after every batch so that if the transaction failed or instance died, I will continue from the last page. But with the below code, it is not updating the page until all batches are completed so when restarting the job, it's processing from page=0.

@Transactional
public void process(long id) {
    Entity entity = repo.findById(id);
    processBatch(entity);
}

void processBatch(Entity entity) {
    int totalPages = otherMicroService.getTotalPages(id);
    int lastPage = entity.getPage();
    for(int page=lastPage; i<totalPages; i++) {
        doOperation();
        entity.setPage(page);
        repo.save(entity);
    }
}


@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<Entity> findById(int id);

Is there a way to update the page after every batch with PESSIMISTIC_WRITE enabled?

Thanks in Advance.

I'd add @Transactional(propagation = Propagation.REQUIRES_NEW) to the processBatch so the data will be committed at every iteration (btw, save and saveAndFlush will work the same in this case).

Be aware that after adding this annotation the processBatch method needs to be moved to the separate bean (or bean's self-injection should be made) in order to make Spring AOP work correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM