Question

I have a NHibernate-mapped class that holds binary data bound to a file on disk. Business logic is very simple:

  • When object is stored in the database, the blob is written to a file properly named to match object ID
  • When object is loaded from DB, blob is filled with file contents
  • When object is deleted from DB, file is deleted too

I used an IPostDeleteEventListener to handle the three situations

The only problem is that if the transaction, for some reason, is rolled back after Session.Delete() the file has been already deleted but the record is kept into the DB, which results in FileNotFoundException when application tries to (re)load the non-deleted object.

Also, but that's not a big matter, if transaction is canceled after insert, I get a garbage file.

What can I do to perform these file system operations only when the transaction is being committed?

[Add] MAYBE... I said maybe, I found a workaround. The ITransaction interface exposes a RegisterSynchronization method which accepts an interface as argument. MAYBE that can be the workaround: storing/deleting the file only after completion of transaction. I need to investigate more, but it seems there is no engineered way to hook to commit/rollback directly from NHibernate event listener subsystem.

Was it helpful?

Solution

Since the filesystem is not transactional and there's no "post-commit" event exposed, it's better to do it outside of NH's event system (i.e. in a higher-level layer)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top