Let's say we have one to many relationship between Customer and Phone..
class Customer{
@OneToMany(cascade = {CascadeType.ALL},mappedBy = "customer", fetch = FetchType.LAZY)
@Fetch( FetchMode.SELECT)
private List<Phone> phoneList;
}
In the above code, what is the difference between fetch = FetchType.LAZY and FetchMode.SELECT.
I read it that they both are same i.e. they both lazily loaded the underlying collection.
Can somebody explain me which one to use when?
If the Hibernate annotation @Fetch is not present on a field, then the default FetchMode for this field is: if this field has FetchType = EAGER, then FetchMode = JOIN. Otherwise, FetchMode = SELECT.
The FetchType. LAZY tells Hibernate to only fetch the related entities from the database when you use the relationship. This is a good idea in general because there's no reason to select entities you don't need for your uses case. You can see an example of a lazily fetched relationship in the following code snippets.
Default fetch for single valued association is "join". Default fetch for collections is "select".
Hibernate uses a fetching strategy to retrieve associated objects if the application needs to navigate the association. Fetch strategies can be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
Fetch type (lazy/eager) refers to when Hibernate will fetch the association, whether in advance when it fetches the entity (eager), or whether it waits for the code to ask for the association (lazy).
Fetch mode (select/join) refers to how Hibernate will fetch the association, i.e. does it use an extra SELECT statement, or does it use a join.
Some combinations of these make no sense, e.g. lazy+join. If you use lazy fetching, then SELECT fetch mode is the only one that you can do.
If you use eager fetch, then you can choose to use either fetch mode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With