Hi folks, I have a question on the correct way of keeping track of historical copies of an entity in database based on JPA+Hibernate:
We have an entity in the database with a composite key based on a (generated) ID and the timestamp when this entity is saved into a table. This entity has a one-to-many relationship with another list of entities as follows: Entity1 -> one-to-many ->Entity2
Application keeps track of Entity1 and historical instances of it. Example:
Timestamp1 : Entity1 is being stored for the first time into table based on pk(ID1, Timestamp1). A list of Entity2 objects is also saved into database based on the one-to-many relationship between Entity1 and list of Entity2 items.
Timestamp2: Entity1 is being retrieved, and run again. Based on this new run, a new instance of Entity1 with a composite id (ID1, Timestamp2) needs to be saved into database. Naturally all relationships with the list of Entity2 items needs to be maintained properly and updated properly as well.
As you can see, an Update operation on Entity 1 does not update the original entry but needs to create a new entry in the database, and also maintain /update related items (Entity 2 list).
So far, I can think of following solutions:
1- Each time such an update takes place, clone the Entity and insert it into database as a new entry. For this you need to implement the logic in code and use the transaction manager to perform the new insert. This means not only cloning Entity1, but also all related associations (list of Entity2)
2- Make sure before the update takes place Entity1 in memory is detached from transaction (evict), and inserted as a new entry into database. I am not sure if this will work seeing the relationship between Entity1 and Entity2 list.
My question is: Is there a smart way in Hibernate to do this? e.g. be able to specify when you want to save the object as a new entry or not, and make sure historical data and related associations are kept properly for the new entry as well as the historical objects?
Thx, M
|