Hi,
I am experiencing troubles with bidirectional associations. I use scaffolding code as proposed in Hibernate in Action (page 108):
Code:
dealUnit.setTgrunit(tgrunit);
tgrunit.getDrddealunits().add(dealUnit);
However, as there may be lots of dealUnits to one tgrunit, the second line of code loads MANY dealUnits into memory, which I do no really need.
The following is now stated in the Hibernate FAQ:
Quote:
Why does Hibernate always initialize a collection when I only want to add or remove an element?
Unfortunately the collections API defines method return values that may only be computed by hitting the database. There are three exceptions to this: Hibernate can add to a <bag>, <idbag> or <list> declared with inverse="true" without initializing the collection; the return value must always be true.
If you want to avoid extra database traffic (ie. in performance critical code), refactor your model to use only many-to-one associations. This is almost always possible. Then use queries in place of collection access.
So I see three possible sollutions:
- use bags instead of maps
- make the association unidirectional
- just remove the second line of my code above
I think that solution 3 is not really elegant, although it works. However, can anybody tell me what his experience with this problem is? It seems to me that making the association unidirectional will in most cases be the right thing to do, because in most cases there will be more than just a few items on the n side, and it will hardly ever be sensible to work with collections with thousands of items.
regards
Stefan