Question

I have this doubt in HQL queries

"SELECT c from Account c inner join c.person " 
"SELECT c from Account c inner join fetch c.person"

Are equals?...When I can use fetch ?

Thanks in advance.

Was it helpful?

Solution 2

what Koitoer has mentioned is correct

Additionally In your Account person is normally set to load lazily, even if you join it in the HQL, the collection person may not load, you have to use 'fetch' to load them.

OTHER TIPS

Fetch join allow to load collection eagerly, it is commonly used when you have relationship that involves collections. It is a way to retrieve eagerly all the records to avoid any problems if the session is closed or you move your object to the view.

FETCH JOINs

NOTE: Assuming person is an object inside your Account class

"SELECT acc from Account acc inner join acc.person"

In this case, Hibernate will return you all the Account objects that definitely have a person associated with them (i.e. acc.person is not null).

However, if your use case requires you to do acc.getPerson() later on in your code, then Hibernate will internally run another query to fetch the Person object associated with acc [provided session was still open].

Hence, in order to save that additional query, it is better to use

"SELECT acc from Account acc inner join fetch acc.person"

when you know that you will need to use the associated object (Person object in this case) later on.


Also please refer the answers in here for better understanding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top