Change Hibernate Discriminator
Problem
You have in your system a business rule that specify that one entity is deleted physically from the DB and now this rule change and the application need to keep this entity for a future use.
Many times as a programmer I experimented business change when an user decide that he need to keep the deleted entities in the system for auditory or any other reason.
There are many manners to encourage this issue, I’ll mention some of these strategies but aren’t in the scope of these document to mention all the possibilities:
1. Create another table with the same structure of the original and move all the deleted entities for this new table. This is useful but in the system if many entities support these behavior you need to duplicate a lot of tables and maintain all at the same time.
2. Introduce a field in the table that indicate the state of the entity, in our case we can use the values “ACTIVE” and “DELETED” as a self explained values of the state of our entity. This is useful solution that you need to take in care, for sure you also need to consider the amount of data that you store in this table and evaluate a possible down of the system performance if the size of this table is too big.
3. Any other.
In our sample I’ll consider the second option, so suppose that you decide that the best strategy for your system is to introduce a new fields in the entity that indicate if is ACTIVE or DELETE.
For sure you need to analyze the cost to made the changes in the system due these mean that now you need to change all the queries (HSQL or Criteria in Hibernate) to filter this entity by the “ACTIVE” value. This change can be very stressful and dangerous due you can introduce a lot of problems in your system.
In this sample I explain a manner to deal with this issue, I known that Hibernate provide any other manners to filter a entity (such as use a filter or the select attr), but for sure there are many cases where you may need to change the discriminator of an entity instance. I select the idea to deal with a mark as deleted object just as a sample.
Warning: not completed yet, I need to make some changes and I open to any comment and suggestion.
Links:
- Full document