user1127214
user1127214

Reputation: 3177

what is difference between lazy="true" and fetch="select" in hibernate?

The lazy=true attribute is enable lazy loading of the parent and child collections and same thing fetch="select" attribute. Is there any difference between lazy="true" and fetch="select" in hibernate?.

Upvotes: 14

Views: 43854

Answers (3)

sreenivas
sreenivas

Reputation: 11

To solve n+1 select problem for n queries (parent child relationship) in hibernate we use fetch="join" instead of fetch="select" . Lazy setting decides whether to load child objects while loading the parent object. You need to do this setting respective hibernate mapping file of the parent class. lazy="true" means not to load the child. By default the lazy loading of the child objects is true.

Upvotes: 1

Chiranjit Dutta
Chiranjit Dutta

Reputation: 171

When we say fetch="select", then it will always fire separate queries to retrieve the association objects even if it is lazy ="false".

But when we say lazy ="true", it means that it will retrieve the association objects in a separate query, but not at the time of loading the object, but when the association is first accessed. We can do it by saying list().size().

When we say fetch="join" it will always fire a single query to get the association objects from the database.

Upvotes: 15

hvgotcodes
hvgotcodes

Reputation: 120168

Yes.

The lazy attribute tells hibernate when to get the children.

The fetch attribute tells hibernate how to get the children.

When you say

The lazy=true attribute is enable lazy loading of the parent and child collections and same thing fetch="select" attribute

that is flat out incorrect. The select fetch strategy is NOT the same thing as turning lazy loading off. In fact, from the documentation

Select fetching: a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you access the association.

Upvotes: 23

Related Questions