hibernate Don't use EAGER fetch type


Example

Hibernate can use two types of fetch when you are mapping the relationship between two entities: EAGER and LAZY.

In general, the EAGER fetch type is not a good idea, because it tells JPA to always fetch the data, even when this data is not necessary.

Per example, if you have a Person entity and the relationship with Address like this:

@Entity
public class Person {

  @OneToMany(mappedBy="address", fetch=FetchType.EAGER)
  private List<Address> addresses;

}

Any time that you query a Person, the list of Address of this Person will be returned too.

So, instead of mapping your entity with:

@ManyToMany(mappedBy="address", fetch=FetchType.EAGER)

Use:

@ManyToMany(mappedBy="address", fetch=FetchType.LAZY)

Another thing to pay attention is the relationships @OneToOne and @ManyToOne. Both of them are EAGER by default. So, if you are concerned about the performance of your application, you need to set the fetch for this type of relationship:

@ManyToOne(fetch=FetchType.LAZY)

And:

@OneToOne(fetch=FetchType.LAZY)