What the heck is a Fetch Type?

Great question! Hibernate is a very handy framework for removing your need to fully understand SQL, but it will force you to understand things such as joins.

Joining two tables in SQL is the foundation of a relational database, as joins allow you to actually define relationships between tables (objects).

Having said that, relationships are important to understand when talking about fetch types in Hibernate. This is the case because whenever you define a relationship in Hibernate, you’ll also need to define the fetch type. The fetch type essentially decides whether or not to load all of the relationships of a particular object/table as soon as the object/table is initially fetched.

An example of this would be as follows, consider this User object:

view plaincopy to clipboardprint?

  1. public class User  
  2. {  
  3.   import javax.persistence.OneToOne;  
  4.   import javax.persistence.JoinColumn;  
  6.   private String username;  
  7.   private String password;  
  8.   private Profile userProfile;  
  10.   // omitting code for getters and setters for username, password  
  12.   @OneToOne  
  13.   @JoinColumn(name="user_profile_id")  
  14.   private Profile getUserProfile()  
  15.   {  
  16.     return userProfile;  
  17.   }  
  19.   private void setUserProfile(Profile userProfile)  
  20.   {  
  21.     this.userProfile = userProfile;  
  22.   }  
  23. }  

Can you spot the relationship in this User object?

If you can’t, no worries, there’s an easy way to spot it!

Any time you see a @OneToOne, @OneToMany or @ManyToMany annotations, you’ve got a relationship. What’s important to note is that the fetch type should be specified within those annotations, if you don’t specify one then it defaults to FetchType.LAZY.

What this means is that when you load up an instance of the User class via a Hibernate query, Hibernate will NOT load this User’s Profile unless you explicitly ask it to. So this means that if you try to call user.getUserProfile(), you’ll get a NULL.

asked Jul 1, 2015 in hibernate by rajesh
0 votes

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.