Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using fetching mode in hibernate

Tags:

hibernate

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?

like image 526
Anand Avatar asked Jan 21 '12 14:01

Anand


People also ask

What is Hibernate default fetch mode?

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.

What is the use of fetch mode lazy in Hibernate criteria?

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.

What is the default fetch mode for one to many association in Hibernate?

Default fetch for single valued association is "join". Default fetch for collections is "select".

What is fetch strategy?

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.


1 Answers

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.

like image 78
skaffman Avatar answered Oct 21 '22 04:10

skaffman