I'm experiencing an issue with the order of database insertions in my Spring application. I have a service method annotated with @Transactional to ensure atomicity and consistency. However, sometimes the order of insertions is inconsistent, and records that were supposed to be inserted earlier end up being inserted late, i'm using a websocket end-point to insert messages using this service method "saveUserMessage" this problem happens only if i invoked this end point very fast, i hope someone can help
@MessageMapping("/send")
public void send(
@Payload MessageRequestDTO messageDTO,
@Header("simpSessionId") String sessionId,
SimpMessageHeaderAccessor headerAccessor
) {
// access the header
Principal principal = (Principal) headerAccessor.getSessionAttributes().get(sessionId);
if (!principal.getName().equals(messageDTO.sender())) {
String errorMessage = "You are not eligible to send this message";
messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/errors", errorMessage);
return;
}
try {
MessageResponseDTO messageResponseDTO = new MessageResponseDTO(
randomUUID().toString(),
messageDTO.conversationId(),
messageDTO.sender(),
messageDTO.receiver(),
messageDTO.message(),
"PENDING",
new java.util.Date().toGMTString(),
new java.util.Date().toGMTString()
);
messagingTemplate.convertAndSendToUser(messageDTO.receiver(), "/queue/private", messageResponseDTO);
messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/private", messageResponseDTO);
messageService.saveUserMessage(messageDTO);
} catch (Exception e) {
messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/errors", e.getMessage());
}
}