简体   繁体   中英

join fetch not working in Hibernate Query Language

I want to retrieve all the records in One database hit and for that, I am using join fetch statements below is my Query

String q = "SELECT oneChat from " + Chat.class.getName() + " oneChat "
                + " join fetch oneChat.user1 " 
                + " join fetch oneChat.user2 "
                + " join fetch oneChat.user3 "
                + " join fetch oneChat.groupData "
                + "where oneChat.dmlStatus != :dmlStatusValue"
                + " AND group_id = :groupIdValue" + " AND reference_id = 0"
                + " AND root_chat_id = oneChat.chatId";

There are total 4 foreign keys/Joins in my table so I added the join fetch statement but its not working ie not returning anything how ever if I remove the join fetch statements I get the result set. My Fetch on table joins is by default Eager ( didn't changed it to Lazy).

Also there's no sql syntax error in the Log file. Am I missing anything ?

Update: It is because the second join ie user2 is returning null so I wasn't getting any data. Now if anyone could tell me how can I counter this, the query should be independent it shouldn't rely on data.

IF you want to return results regardless of data being present on the dependencies, then you should use left join instead of inner join (join fetch is equal to inner join fetch):

"SELECT oneChat from " + Chat.class.getName() + " oneChat "
                + " left join fetch oneChat.user1 " 
                + " left join fetch oneChat.user2 "
                + " left join fetch oneChat.user3 "
                + " left join fetch oneChat.groupData "
                + "where oneChat.dmlStatus != :dmlStatusValue"
                + " AND group_id = :groupIdValue" + " AND reference_id = 0"
                + " AND root_chat_id = oneChat.chatId";

Now when the OneChat does not have any user2 dependency on the database, the query will still return results regardless of that.

Just on the side.. if you are using prefixed, then try to add prefixes to group_id and root_chat_id fields in the where clause for clarity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM