Skip to content

Instantly share code, notes, and snippets.

@dksingh04
Last active August 26, 2020 07:06
transactionoperation using Spring-data and mongoTemplate
@Transactional(value = "mongoTransactionManager", propagation = Propagation.REQUIRED)
@Retryable(value = {MongoCommandException.class, MongoException.class}, exclude = {MongoTransactionException.class, UncategorizedMongoDbException.class},
backoff = @Backoff(delay = 10), maxAttempts = 10)
public void performingTransactionaOperations(DocumentBean1 document1, DocumentBean2 document2, DocumentBean3 document3){
try {
mongoTemplate.insert(document1);
mongoTemplate.insert(document2);
mongoTemplate.insert(document3);
}catch (MongoTransactionException | UncategorizedMongoDbException ex){
MongoException mongoException = null;
if(ex.getCause() instanceof MongoException) {
mongoException = (MongoException) ex.getCause();
}else if(ex.getCause() instanceof MongoCommandException){
mongoException = (MongoCommandException) ex.getCause();
}
if(mongoException!=null && mongoException.hasErrorLabel(MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)) {
System.out.println("TransientTransactionError aborting transaction and retrying ...");
throw mongoException;
}else if(mongoException!=null && mongoException.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)){
log.debug("UnknownTransactionCommitResult, retrying commit operation ...");
throw mongoException;
}
throw ex;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment