JOIN vs JOIN FETCH
Consider the query below:
List<Individual> individuals = session.createQuery("select i from Individual i left outer join fetch i.roles " +
" left outer join fetch i.credentialUPs " +
" join i.properties p " +
" where p.individualIdPropertyName.name = :emailType and p.value = :emailAddress")
.setParameter("emailType", "EMAIL_ADDRESS")
.setParameter("emailAddress", emailAddress)
.list();
This will select “credentialUP” and “roles” during the query. Interesting thing happens with “properties” association. The query will select an entity according to the where statement provided, however “properties” won’t be available by default.
To make Hibernate load all “properties” of an object we’ll need to call those properties explicitly within the current session.
Ex:
int size = individuals.size();
if (size == 1) {
Individual result = individuals.get(0);
result.getProperties().isEmpty();
return result;
}
This will result in Hibernate making additional “select” calls to fetch a required associations.
Now consider doing call like this:
List<Individual> individuals = session.createQuery("select i from Individual i left outer join fetch i.roles " +
" left outer join fetch i.credentialUPs " +
" join fetch i.properties p " +
" where p.individualIdPropertyName.name = :emailType and p.value = :emailAddress")
.setParameter("emailType", "EMAIL_ADDRESS")
.setParameter("emailAddress", emailAddress)
.list();
Here, as we’ve explicitly specified that we want to “join fetch” this association, it will not do additional selects. We will however get only one “property” entity, the one that matches our “where” condition (even though there might be many more associated “properties”). Also, as expected, it doesn’t matter if we do or don’t call the “isEmpty” within the session. It also doesn’t matter if we do “left outer join” or a regular “join”