Home > OS >  Should I fetch join all the entities that are lazily loaded?
Should I fetch join all the entities that are lazily loaded?

Time:10-14

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();

CodePudding user response:

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.

  • Related