spring-data-mongodb
spring-data-mongodb copied to clipboard
Annotation @version is not working in mongodb BulkOperations insert operation
Annotation @version is not working in mongodb BulkOperations insert operation but working with mongoRepository insert.
Below is the code for BulkOperations and MongoRepository:
@PostMapping("/using-repository")
public ResponseEntity<Documents> createDocument(@RequestBody Documents documentsRequest) {
Documents _document = documentsRepository.insert(new Documents(documentsRequest.getTitle(), documentsRequest.getDescription()));
return new ResponseEntity<>(_document, HttpStatus.CREATED);
}
@PostMapping("/using-template")
public ResponseEntity<List<BulkWriteInsert>> createUsingTemplate(@RequestBody Documents documentsRequest) {
Documents _document = new Documents(documentsRequest.getTitle(), documentsRequest.getDescription());
List<Documents> validDocuments = new ArrayList<>();
validDocuments.add(_document);
BulkOperations bulkOperations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Documents.class);
bulkOperations.insert(validDocuments);
return new ResponseEntity<>(bulkOperations.execute().getInserts(),HttpStatus.CREATED);
}
Below is the entity class
public class Documents {
@Id
private String id;
private String title;
private String description;
@CreatedDate
private Date createdAt;
@LastModifiedDate
private Date lastUpdatedAt;
@Version
private Long version;
public Documents() {
}
public Documents(String title, String description) {
this.title = title;
this.description = description;
}
Issue Screenshot Link: https://github.com/sriramkishoren/spring-boot-mongo-version-issue/blob/main/Screen%20Shot%202022-06-12%20at%2010.08.41%20AM.png
Bulk operations use a low-level bulk mechanism to run a batch of insert/update/upsert/delete operations. Optimistic locking doesn't work well in such a scenario because the actual update happens at a later time while versioning details need to be maintained meanwhile.
We do not have a mechanism to return immutable updated objects because the API for insert returns BulkOperations. You can end up with a state where the object is prepared for an insert with the version counter incremented, but you never executed the bulk and so your in-memory state is inconsistent.
Updating objects isn't supported either through the Bulk API as Bulk updates require Update and Query objects instead of entities.
We should document these limitations.