JPA Lazy Collection Loading

If all you are looking for is how to load a lazy collection with JPA, you’ll be swamped with endless posts and articles going on about the pros and cons of using lazy or eager loading. Its all noise if your question is simply how do I load my lazy collection using the JPA API?

The quick and dirty answer is just do this: singleFoo.getBars().size();

There it is. End of story. It is worth noting that I’m an advocate of using a Service Facade and DTOs, in other words clean APIs and I use Spring’s transactional annotations on the service layer. Also, you will come across posts mentioning Hibernate and initialization methods, this doesn’t help since we are only interested in pure JPA here.

Sure there is alot more to it and there are pitfalls to consider, that is old news, any layer of abstraction comes at it price and in some way dumbs you down (mmm, getting philisophical, its so easy to do).

This is one of the posts I was referring to, and it was a distraction: Avoid Lazy JPA Collections. A better read would be this one: JPA Implementation Patterns: Lazy Loading

2 thoughts on “JPA Lazy Collection Loading

  1. That’s a hack, that’s risky. Even using Hibernate.initialize(..) may not be a good idea. The reason is, an entity in the lazy collection may have lazy mappings itself. Simply calling .size() will fetch the elements of the collection, but their members will remain lazy. You’ll end up calling .size() a couple of times recursively, if you want your object serialized properly, for example. That’s why you should generally avoid jpa collections altogether.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s