Is there some "on removal" action in Hibernate triggered by e.g. orphan removal or its equivalent?

StackOverflow https://stackoverflow.com/questions/14857586

Question

I have model SomeFileModel that contains reference to a file stored on disk. I would like to save that file together with an entity and delete them both at once. While the former isn't difficult, the problem comes with the latter: SomeFileModel is in relation many-to-one with another model FilesCollectionModel and is annotated with orphanRemoval = true.

While service responsible for SomeFileModel removes that file, when we order destroying entity, other services (as one would expect) don't do that. Of course, I could make all models have some prepareDeleteion() method, that would be called by cascade, but I don't think it's the best possible approach.

My question is: is there some annotation, or other convention that would mark method, as to be called on entity deletion? It it even possible? Or should I rather use some other solution e.g. "orphaned files collector" that would remove files without references in database, or that ugly cascade method call? What approach would be the best?

I use Hibernate 4 and Spring Framework 3.1.0 if that helps.

Was it helpful?

Solution

Yes ,Short answer is Interceptors and Events

As per Hibernate docs :

Interceptors :

 The Interceptor interface provides callbacks from the session to the app, 
 allowing the application to inspect and/or manipulate properties of a
 persistent object before it is saved, updated, deleted or loaded.

Events :

The event system can be used in addition, or as a replacement, for interceptors.
All the methods of the Session interface correlate to an event.
You have a LoadEvent, a FlushEvent, etc. 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top