views:

43

answers:

2

I have a Java program that writes results to 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!

+4  A: 

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

p.campbell
Throw in some XA to do two phases commit and you're done! http://matthewneale.net/2008/11/27/an-xa-filesystem/
Guillaume
Does TxFileResourceManager work on top of a non-transacted filesystem?
Remus Rusanu
+1 for showing me something I wanted to implement for myself exactly 3 days ago...
Daniel
A: 

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.

Daniel