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
1
Personally I’d do the simplest thing that could possibly work: Don’t auto-fix the bilateral relations.
I’ve previously developed and maintained a system that (among many other things) did exactly this: ensure that the relations between business objects where always in sync with what the DB would look like (i.e. if you remove one item, the other is updated accordingly). It was quite a complex piece of code and it was pretty hard to keep all the corner cases in mind (it didn’t help that this also supported nested transactions).
But if your business transactions are well defined and work pretty much independently from each other and each one is run in its own transaction, then all that complexity brings very little advantage.