0

I am currently working on a web project using JPA and queryDSL.

As far as I know, fetch join is used to reduce the number of SQL sent to DBMS when executing lazy loading. (Since fetch joined entities are included in the persistence context)

If so, should all of the entities that are lazily loaded in the service layer be called with fetch join?

For example, a posting community that has a chatting system...

Chat room table.
ChatRoom (Long id, Member memberFrom, Member memberTo, Post post) 
// post is where the chat starts from. The members can start a chat from the post.

API that requests the chat room list only needs to join with the entity of memberFrom and memberTo. So from the functional aspect of view, the query below meets the condition.

return query.select(chat)
        .from(chat)
        .innerJoin(chat.memberFrom, member).fetchJoin()
        .innerJoin(chat.memberTo, member).fetchJoin()
        .where(chat.memberFrom.email.eq(email).or(
               chat.memberTo.email.eq(email)))
        .fetch();

But DTO that will be returned also needs post and message entity so they will be lazily loaded in the service layer. In this case, should I also fetch join the message and post entity like below?

return query.select(chat)
        .from(chat)
        .innerJoin(chat.memberFrom, member).fetchJoin()
        .innerJoin(chat.memberTo, member).fetchJoin()
        .innerJoin(chat.messages, message1).fetchJoin()
        .innerJoin(chat.post, post).fetchJoin()
        .where(chat.memberFrom.email.eq(email).or(
               chat.memberTo.email.eq(email)))
        .fetch();
Roger
  • 7
  • 3

1 Answers1

0

That dependens entirely on if the joined associations are actually read / used. If their unused, its fine to leave these uninitialized and they won't cause any extra SQL statements to be executed. Instead, Hibernate will proxy these fields.

  • So you mean it is always preferred to use fetch join over join if the joined associations are used? – Roger Oct 07 '21 at 08:40
  • It depends on the multiplicity of the associations and the complexity of the join product. To-one relations can usually be eager loaded without issues. Optional one-to-one relations have to be eager loaded. Multiple to-many assocations cannot be eager loaded in the same query regardless. Entities with large table spans (join tables, secondary tables or table inheritance) might produce such complex queries when joined, that it produces are faster query plan when fetching the association seperately. – Jan-Willem Gmelig Meyling Oct 07 '21 at 09:02