I have a one User - one Channel relationship
(@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
The channel has an avatar, which is stored on the local drive, and the database stores the path to the photo.
Where and how would be the best place to remove the file from the local drive when removing the Channel? In Facade, Service or check once a day if the database contains an entity and the folder corresponds to it and if the folder is there but the entity is not, then delete it?
At the moment I delete simply with the entityManager, but it does not delete the photo from the local drive
repository.deleteById(id);
I'm sorry if I didn't phrase the question correctly, I'm just not very experienced at it and I tried to describe the problems in as much detail as possible.
CodePudding user response:
You can do it on the service layer but please consider the following:
- first delete entity and then the action to delete the photo
- Both actions (delete entity, delete photo) are inside the same transaction probably marked with
@Transactional
in your service method. This way if something goes side ways the database action is rolled back and you can try again later.
the other solution mentioned, having a job scheduled in the application which regularly inspects the folder with photos and deletes any non used photo, sounds also good but in this case consider carefully the following
- This must be in sync and carefully done, because I suspect you already have another process to insert photos in the system. This other process logically first saves the photo in the disc and then creates the entity. If those 2 processes happen to be at the same time you have the risk of eliminating a photo that was to be used for a new user and the entity was not yet created. So you have the risk of identifying a photo as to be deleted when in actuality it was not yet persisted as entity.