Greetings!
I would like to discuss managing java bi-directional relationships with ehcache.
My situation is:
- legacy data model (batch updates from external source)
- data is versioned (configured in mapping)
- managing the relationships manually (ie no transitive persistence)
My problem is: cached childs parent is null e.g.
Sess1 --> session.persist(parent);
Sess2 --> session.persist(child);
Sess3 --> session.query( returns child )
View --> child.getParent(); // <--- parent is null
Even with agressive fetching to query the child, the parent is null. I *thought* this is because hibernate loads the child entity from ehcache (which has a null reference to parent).
One solution may be to evict the child or even simpler I just create the object reference as described in the FAQ:
Quote:
How can I create an association to an entity without fetching that entity from the database...following code does not result in any SELECT statement:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
This relates the persistent parent entity (Item) to a transient child (Bid), so the parent can be accessed later off the *cached* bid entity.
As the FAQ states there is no SQL .... good for performance !
BUT.....
2. This FAQ says that both sides should be referenced:
Quote:
When you update a bidirectional association you must update both ends.
parent.getChildren().add(child);
child.setParent(parent);
Now, when I add the child (Bid) to the parent (Item) collection of bids, hibernate does:
- executes extra select statements, (N+1) on the association ?
- executes update statements on the parent (I think its updating the version even though the actual DB row hasn't changed)
Is doing this performant? worthwhile ?
3. Then in another FAQ says:
Quote:
Why does Hibernate always initialize a collection when I only want to add or remove an element? ... , refactor your model to use only many-to-one associations...use queries in place of collection access.
Is the extra selects and updates somehow due to using Set rather than List (for instance?).
Currently I am NOT maintaining one-to-many side, and turned off any caching of collections, then I just fetch the collections when I need, and I dont have the parent updated unnecessarily.
I would like to know what others would do in this situation, if I'm doing the right thing or if I've misunderstood something with my bidirectional mappings
Thanks
Paul