JPA / Spring Roo: is there a destructor event raised when an entity is removed from persistent storage?

I have an Image object (Spring Roo / JPA) that references images stored in the file system. I would like to delete these files when the Image object is removed from the repository.

I can write a method remove()for each image object that will make it delete itself and the files it refers to, but this will only work when the image is manually deleted using this method. Obviously, this will not work if the image is deleted in a cascade when deleting the owner object or deleting it by calling entityManager.remove()on it.

Is there any method or event raised when an object is deleted from the database?

+3
source share
1 answer

Yes there is. In general, these methods are called lifecycle callback methods . In your case, you need to remove the callback method. This can be located to split the class (link to it via the @EntityListeners annotation) or directly to your entity:

@PostRemove
protected void postRemoveOperations() {
    //remove images here
} 

Or depending on the details, @PreRemove may be more useful.

+3
source

All Articles