Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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
JavaRanch » Java Forums » Java » Performance
Bookmark "Hibernate performance" Watch "Hibernate performance" New topic
Author

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) ??

Regards,

Robert
Paul Sturrock
Bartender

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 ??

tks...
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

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

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


Or if you understand French

http://arodrigues.developpez.com/tutoriels/java/performance/hibernate-performance-part1-strategies-chargement/
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2854
    
  11

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Hibernate performance