How to Properly use Lazy Loading w/ Spring
So having outlined the differences between these two approaches, I hope you realize that Lazy loading is a suggested route to take your application code in most scenarios. So having said that, how do we make use of Lazy loading with a Spring enabled application?
The important thing to remember is that when using a Spring/Hibernate application, there‚Äôs a bit of code that is handled for you in the background that you don‚Äôt actually see. The code that you don‚Äôt see is the transactional code (enabled by the¬†@Transactional¬†annotation in your DAOs) and this is something that you always need to keep in mind when using Lazy loading.
Having said that, let‚Äôs take a look at an example of Lazy loading using our¬†User¬†object. Let‚Äôs assume we have our¬†User¬†object which has a Lazy load fetch enabled to the¬†Profile¬†object. So we will need to design our¬†UserDao¬†with this relationship in mind. One approach is to create two separate getter methods like so:
In the code above you see that we have created two getter methods to load the¬†User¬†object from our database via Hibernate.
This means that when you want to load a¬†User¬†object without any relationships (i.e. when you‚Äôre checking to see if the login information is valid) then you can call¬†getUserById¬†and this will bypass the unnecessary join to the¬†Profile¬†object/table. But if you are in a situation where you DO need to refer to the¬†User‚Äės profile, then you can call the¬†getUserWithProfileById.