Issue
i am developing one ERP system for small and medium sized organization, i stuck when comes to delete operation for entities.
Right now i have one Project entity and Task entity, i.e. one project has many Tasks
now i have three options while delete operation is performed.
1> either delete data permanently from database, with child data
i.e. if project is deleted then also delete it's associated tasks
here problem is : we won't be able to get back, once it is deleted.
2> either only set isDeleted to true.
here problem is : if any entity has isDeleted to true, then it's associated entity can fetch it through Getter method (so it is not a good idea)
if Project P1 has three tasks T1, T2, T3, with Fetch Type EAGER.
e.g. if i set Task T1 as isDeleted to true then, if i get project P1 it will also get three tasks along with T1, because still there is a relationship between them, T1 is only updated to isDeleted to true.
3> or store all events(CRUD) of an entity in separate history tables
here problem is : database size will be in multiple times then regular database.
Solution
Instead of Actually deleting the data, and better than isDeleted, try deletedDate. If deleted_date is null, product is active. If not, The date on which it is deleted will be set.
Now on the entity, just write
@DynamicInsert
@SQLDelete(sql =
"UPDATE post SET deleted_date=now() " +
"WHERE id = ?")
@Where(clause = "deleted_date IS NULL ")
class User{
}
here, @SQLDelete
will make sure when you call the delete method, It doesn't actually delete the entity, but sets its deleted date to when it was deleted.
@Where
cause will make sure whenever any entity is called, it adds the code AND deleted_date IS NULL
to its corresponding hibernate query fired, so only the non deleted ones will be fetched.
Answered By - Rohan Shah
Answer Checked By - Gilberto Lyons (JavaFixing Admin)