Tuesday, February 19, 2008

Be careful with @OneToOne and lazy loading

When modelling an entity one sometimes wants to have information in a separate table even if it would exist only one time for a given entity. Think of a 1:0...1 composition. This could be handled as embedded in the primary entity, but perhaps you don't want to do this as the dependent object is huge and you don't always need it. The dependent table could even live in a different table space for that reason. Or just for relational normalization reasons.

For the @xxxToOne relations, JPA 1.0 spec sees Eager loading as default. One can give a *hint* that the dependend end should be lazily loaded, but this is only a hint.

Now when you have an optional @OneToOne relation, Hibernate (at least) needs to do an additional select for that relation to find out if the dependend object is null or not. For a mandatory (1..1) relation it can just install a proxy to lazily load the relation, but this is not possible for 1...0..1.
See e.g. http://www.hibernate.org/162.html for an explanation.

No comments: