Reputation: 1
I have some bogus activity occurring in my code because of incomplete transactions and I'm not sure what to do about it.
For example, if I have:
User user = new User();
userService.save(user);
Email email = new Email(user, "Welcome!");
emailService.send(email);
and the server dies after saving the user
but does not get to send the email then how can I revert the transaction?
Furthermore, to make things even more complex, let's say we sent the email first and then persisted the user afterwards and the email got sent, but the user didn't get persisted. Since that transaction couldn't possibly be reversed, there would have to be a way of managing all the "what-if" cases.
The problem is that it isn't necessarily to do with email only, it could be anything - email, sms, bank transaction, web service call, database procedure call, etc...
Does Java have a way of managing problems like these? I understand that this could be seen as an open-ended question, but the problem is that I don't actually know where to start learning about this problem.
Upvotes: 0
Views: 290
Reputation: 11
I would probably create a separate table for emails to be sent, and let a Quartz or other task scheduler to do the emailing.
In this scenario, you'd insert into both user and email tables at the same time. Check out this: MySQL Insert into multiple tables? (Database normalization?)
So, when you commit the user, the email will be committed at the same time or they will both fail.
Then your scheduler can look at the emails table every xx minutes and soft/hard delete the emails successfully sent. If you soft delete them, you'll also get to have a history of your sent emails. This approach of using a scheduler for emails makes sense to me also because sending emails requires an internet connection unlike creating users on the db.
Upvotes: 1