I know to use lazily load objects/collections outside the session, we do Hibernate.initialize(Object obj)
so that object that is passed as an argument to initialize() method is initialized and can be used outside of the scope of the session.
But what I am not able to understand how this works. I mean if we are doing then we end up in having eager fetching so why we did lazy in the configuration and end up in the eager fetching while runtime.
In other words, I want to know the difference between using Hibernate.initialize()
and eagerly
loading that object.
Did I get it wrong or miss something?
The difference is in scope of application.
The reason for making a collection association lazy is to avoid having it load the collection every time the parent object is loaded if you don't really need it.
If you are lazy-loading a collection normally, but for a particular use, you need to ensure the collection has been loaded before the session is closed, you can use Hibernate.initialize(Object obj)
as you noted.
If you in fact always need the collection loaded, you should indeed load it eagerly. In most software though, that isn't the case.