Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


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;  
  5.   
  6.   private String username;  
  7.   private String password;  
  8.   private Profile userProfile;  
  9.   
  10.   // omitting code for getters and setters for username, password  
  11.   
  12.   @OneToOne  
  13.   @JoinColumn(name="user_profile_id")  
  14.   private Profile getUserProfile()  
  15.   {  
  16.     return userProfile;  
  17.   }  
  18.   
  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
35 views



Related Hot Questions



Government Jobs Opening


...