We have a tricky question in a project using Java & Hibernate, with a model containing bi-directional relationships.
As it's a small project with few users, few entities, and few rows involved in relationships (not more than 100 in 1-n relationships), we don't really need a 2nd level cache.
Operations done with entities are simple: inserting, removing and performing some computations with entities involving relationships loading.
Let say we have two Java entities: Room
and Furniture
. An item of furniture is in one room and a room can have many items of furniture. So Furniture
has a reference to Room
, and Room
has a list of Furniture
.
For the Delete Furniture
action, the easiest thing to do is to retrieve the right Furniture
, and tell the EntityManager to remove the Furniture
. But, to ensure the Java instances remain coherent, we should also remove the Furniture
instance in the list of Furniture
s in the associated Room
. Unfortunately, if the Room
instance is not loaded, a request will be done to the database for nothing if we don't have a cache.
So, what would be a better choice between:
A) Keeping it simple
- In general, no preoccupation about bilateral relationships in java instances coherence, as we don't have 2nd level cache
- Well document the fact that there is a cache per-action, so if specific computations must be done requering bilateral relationships coherence within an action, this action must take care of the coherence
- No boilerplate code for bilateral relationships coherence management needed
- No overhead of loading non-necessary entites
- If a 2nd level cache must be added, then a big effort in refactoring has to be done
B) Keeping it coherent
- Always maintain the bilateral relationship's coherence
- Enable 2nd level cache