Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between inner join and inner join fetch ? ,HQL

Tags:

hibernate

hql

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.

like image 203
user2683519 Avatar asked Feb 03 '14 17:02

user2683519


People also ask

What is difference between join and inner join?

Difference between JOIN and INNER JOINJOIN returns all rows from tables where the key record of one table is equal to the key records of another table. The INNER JOIN selects all rows from both participating tables as long as there is a match between the columns.

Can we use join in HQL query?

HQL Join : HQL supports inner join, left outer join, right outer join and full join.

What is difference between inner join and left join?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table.


3 Answers

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.

like image 42
Zeus Avatar answered Nov 17 '22 18:11

Zeus


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

like image 98
Koitoer Avatar answered Nov 17 '22 17:11

Koitoer


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.

like image 2
Chandan Hegde Avatar answered Nov 17 '22 18:11

Chandan Hegde