JPA chooses vs joins. Are legacy connections made up?

Ok. I know the differences between the two, but I should avoid joins and just use o joinfetch selections, no matter which query is requesting the object's attributes. Let's say I want a list of students in a group. Should I request a group and reach out to students. Or maybe ask the group to join the students. Or both are the same.

I work without bi-directional relationship.


source to share

1 answer

You should use a fetch / fetch join when you want to avoid lazy fetching / forced fetching.

For example, when you query for a group or a list of groups: select * from Group where id=??

Students are not loaded from the database until you do something with group.getStudents (). If you are still inside your transaction, you will be loading students from the database, or if you are outside of a transaction, you will get a lazy fetch exception.

If you nevertheless use:, select g from Group g fetch join g.students

you will immediately download the groups (s) and all their students from the database.

So, should you always use a fetch connection? Not. Only when you need ...

If you know that you will have access to all students of all groups every time, then it makes sense to just have them in one go. If you don't need to refer to students at all, it doesn't make sense to use sampling.

This is also the reason why using FetchType.EAGER in collections is generally a very bad idea!



All Articles