Reputation:
Ok. I know the differences between them but should I avoid joins and just use the fetch o joinfetch whatever the case for query an object attributes. Lets say I want the list of students of a group. Should I query the group and access the students. Or maybe query the group making a join with students. Or are both the same.
I'm working without bidirectional relationship.
Upvotes: 3
Views: 4143
Reputation: 4446
You should use fetch/fetch join when you want to avoid lazy fetching/force eager fetching.
For instance when you query a group or a list of groups: select * from Group where id=??
The students are not loaded from the database until you do something with group.getStudents(). If you are still inside your transaction you will then load the students from the database, or if you are outside a transaction you will get a lazy fetch exception.
If you however use: select g from Group g fetch join g.students
you will load the group(s) and all their students from the database right away.
So should you use fetch join always? No. Only when you need to..
If you know that you will be accessing all the students of all the groups every time, then it makes sense to just get them in one go. If your won't be needing to access the students at all it doesn't make sense to use fetch..
This is also the reason why using FetchType.EAGER on collections is usually a very bad idea!
Upvotes: 5