Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
This is typically accomplished by maintaining a flag indicating whether the process has taken place. Each time the desired object is summoned, the flag is tested. If it is ready, it is returned. If not, it is initialized on the spot.
In case of Hibernate, the lazy initialization is made in the proxy (created in place of collection) using the hibernate session from which the object was obtained. If the collection is accessed when the original session is closed (for example, outside a @Transactional
scope), the LazyInitializationException is thrown.
To initialize the collection, it is enough to call size()
or iterate through all elements.