File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance and the fly likes Hibernate performance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Hibernate performance" Watch "Hibernate performance" New topic

Hibernate performance

Robert Siqueira
Ranch Hand

Joined: Jan 21, 2008
Posts: 37
Hi guys !

What is the best approach about hibernate fetch strategy, use LAZY or EAGER ? Is it better get all data in only once SQL (EAGER) or some SQL queries when you need the data (LAZY) ??


Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

It depends on the data and how you use it, there is no "one size fits all" approach to this.

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Robert Siqueira
Ranch Hand

Joined: Jan 21, 2008
Posts: 37
Ddo you have some source where I can study about this kind of performance hints ??

Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

The Hibernate docs are a good place to start.
Antonio Gomes Rodrigues

Joined: Oct 11, 2010
Posts: 1
Paul Sturrock wrote:The Hibernate docs are a good place to start.

Or if you understand French
Greg Charles

Joined: Oct 01, 2001
Posts: 2771

The worst performance comes when you have LAZY on data that you will be using. So let's say your database has a USERS table and a related ADDRESS table. You retrieve a list of users, and you want to print out their addresses. Hibernate will do one query for the list of users and then one more query for the addresses for each of the users. That's a total of N+1 queries, where N is the number of users. Also know as the N+1 problem, this represents an epic failure in your mappings.

On the other hand, you could put EAGER on the addresses, but what if you rarely actually care about that data. The Hibernate query for users will include a join with the address table, which of course will be slower than a simple query of the users table. If you don't access the addresses, then you've wasted the effort to retrieve them.

Now, it is possible to write Hibernate (and JPA) queries to explicitly join in the addresses where you want them. That will override the LAZY load in the mappings. However, if you forget to do it, then you get the N+1 problem again.
I agree. Here's the link:
subject: Hibernate performance
Similar Threads
join problem in hibernate 3.x
HQL join fetch and $EnhancerByCGLIB$ issue
OutOfMemory Error
LazyInitializationException Help please
what are the disadvantage of Lazy and eager fetching??