I’ve got an Image entity (Spring Roo / JPA) that references images stored on a filesystem. I’d love to remove those files when an Image entity is removed from the persistent store.
I could code a manual remove() method on each Image entity that causes it to delete itself and its referenced files, but that will only work when the image is removed manually using that method. It obviously wouldn’t fire when an image is cascade-removed when an owning entity is removed, or when it’s removed by calling entityManager.remove() on it.
Is there any kind of method or event that’s called when an entity is being removed from the database?
Yes there is. In general those methods are called lifecycle callback methods. In your case you need post remove callback method. This can be located to separate class (referenced then via @EntityListeners annotation), or directly to your entity:
Or depending about details, @PreRemove can be more useful.