hibernate FetchType

hibernate FetchType

Default FetchType

Depends on the cardinality of the relationship

  • All to-one relationships use FetchType.EAGER
  • all to-many relationships FetchType.LAZY

Loading

  • Eager Loading is a design pattern in which data initialization occurs on the spot
  • Lazy Loading is a design pattern which is used to defer initialization of an object as long as it's possible

@Entity
@Table(name = "USER")
public class UserLazy implements Serializable {

@Id
@GeneratedValue
@Column(name = "USER_ID")
private Long userId;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<OrderDetail> orderDetail = new HashSet();

// standard setters and getters
// also override equals and hashcode

}

@Entity
@Table (name = "USER_ORDER")
public class OrderDetail implements Serializable {

@Id
@GeneratedValue
@Column(name="ORDER_ID")
private Long orderId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="USER_ID")
private UserLazy user;

// standard setters and getters
// also override equals and hashcode

}

One User can have multiple OrderDetails. In eager loading strategy, if we load the *User* data, it will also load up all orders associated with it and will store it in a memory.

But, when lazy loading is enabled, if we pull up a UserLazy, OrderDetail data won't be initialized and loaded into a memory until an explicit call is made to it.

List<UserLazy> users = sessionLazy.createQuery("From UserLazy").list();
UserLazy userLazyLoaded = users.get(3);
return (userLazyLoaded.getOrderDetail());


the main difference between the two types of fetching is a moment when data gets loaded into a memory.

With the lazy initialization approach, orderDetailSet will get initialized only when it is explicitly called by using a getter or some other method as shown in the above example:

But with an eager approach in UserEager it will be initialized immediately in the first line of above example:

Pros and Cons

LazyLoading

Advantages:

  • Initial load time much smaller than in the other approach
  • Less memory consumption than in the other approach

Disadvantages:

  • Delayed initialization might impact performance during unwanted moments
  • In some cases you need to handle lazily-initialized objects with a special care or you might end up with an exception

EagerLoading

Advantages:

  • No delayed initialization related performance impacts

Disadvantages:

  • Long initial loading time
  • Loading too much unnecessary data might impact performance

https://www.baeldung.com/hibernate-lazy-eager-loading

Lazy Collection