I have been asked in an interview why hibernate @OneToOne and @ManyToOne uses Eager Loading and @OneToMany and @ManyToMany uses Lazy Loading? What I explained to the interviewer is that as user may not be interested in the List of results and it will take more time to load so by default they are lazy loaded. But interviewer is not satisfied. Could anyone please clearly specify why hibernate community makes them so?
1 Answers
In any @*ToOne
relation the target side clearly may be assumed to belong to the source as a logical part. So it is to be expected that if the target object is being accessed it will only happen to the source object. And it is also like this will happen.
For a @*ToMany
it is difficult to know upfront which of the target object will be needed, or whether all related objects will be needed at some time by the programm loading a source side of the relation. In that case it would be a waste of resource blindly loading related objects.
This default settings will ensure that in most cases the objects likely going to be accessed are present in memory while avoiding loading the whole set of instances at once.
The basic problem that leads to that heuristic is:
What related objects will be nedded and can those be provided efficiently.
In case the default is not apropriate at a certain point in a given datamodel, you may change the settings for lazy loading appropriately.