Hi I'm trying to implement service logic that invoke aws s3 codes after saving data(after commit) to mongodb.
Basically, in @Service class, there's @Transactional method which receives data from client and save the data to mongoDB Altas and then publish event.
But when after-commit event is executed, newly saved data cannot be found and repository returns null.
Here's the code.
DocumentService.java
public Document uploadAndMoveDocument(String email, String fileName) throws IOException { String fileNameNFC = Normalizer.normalize(fileName, Normalizer.Form.NFC); Document document = new Document(); document.setId(UUID.randomUUID().toString()); document.setName(fileNameNFC); document.setOwner(email); document.setFormat(documentUtil.getFileExtension(fileName)); document.setCreatedAt(new Date()); document.setTags(new ArrayList<>()); document.setSharedMembers(new ArrayList<>()); Document savedDocument = documentRepository.save(document); applicationEventPublisher.publishEvent(new DocumentUploadEvent(email, fileNameNFC)); return document; }
DocumentEventListener
@Component@RequiredArgsConstructorpublic class DocumentEventListener { private final S3Service s3Service; private final DocumentService documentService; private final Logger logger = LoggerFactory.getLogger(DocumentEventListener.class); @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void moveDocumentToS3(DocumentUploadEvent event) { logger.debug("transaction event occurred"); Document document = null; try { document = documentService.findDocumentByOwnerAndName(event.getEmail(), event.getFileName()); logger.debug("info : ", event.getEmail(), event.getFileName(), document.getId()); boolean success = s3Service.moveFileToDocuments(event.getEmail(), event.getFileName(), document.getId()); if(!success){ logger.debug("failed"); documentService.deleteDocument(documentService.findDocumentById(document.getId())); throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR); } } catch(Exception e){ logger.debug("error"); e.printStackTrace(); document = documentService.findDocumentByOwnerAndName(event.getEmail(), event.getFileName()); if(document != null){ documentService.deleteDocument(documentService.findDocumentById(document.getId())); } throw e; } } @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void deleteDocumentFromS3(DocumentDeletedEvent event) { s3Service.deleteDocument(event.getEmail(), event.getDocumentId()); }}
When documentService.findDocumentByOwnerAndName(event.getEmail(), event.getFileName()) is invoked, it returns null and because of that, it fails to proceed and throws error.
I don't understand why this happens since in my understanding, event would be executed after uploadAndMoveDocument() is done.
I tried to use TransationSynchronizationManager.Register... thing too but still didn't work.
To me, it seems like even the eventListener is configured to executed after commit, somehow it's being executed before the commit.