I have a Java program that writes results to 开发者_Python百科both a DB (SQL Server) and a spreadsheet (POI), and it would be best if neither is written to if there's an error with either.
It would be a lot worse if the spreadsheet was produced and then an error happened while saving to the DB, so I'm doing the DB-write first. Even so, I'm wondering if someone knows of a way to guarantee they both succeed or fail as a unit.
Thanks!
Consider the Java Common Transaction, which has a File Transaction component.
If you could wrap both the database call and the file write within a File Transaction in a larger encompassing transaction, you might have what you're looking for.
More at http://commons.apache.org/transaction/file/index.html
Use XA transactions to include file-system operations and database operations in the same transaction (hence making them atomic). SQL Server already supports XA; use XADisk for file-system transactions enabled with XA.
We currently use the following approach for send emails in an transaction: The EMails are written to a database table within the transaction, and a helper thread takes them out and sends them asynchronously. The latter can be retried a few times, which makes us really sure that emails leave if they can. Same with calling the Report Server, the FAX server etc.
精彩评论