join fetch 在 Hibernate 查询语言中不起作用

join fetch not working in Hibernate Query Language

我想检索一次数据库命中中的所有记录,为此,我使用下面的连接提取语句是我的查询

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";

我的 table 中总共有 4 个外来 keys/Joins,所以我添加了 join fetch 语句,但它不起作用,即不返回任何内容,如果我删除 join fetch 语句,我会得到结果放。我对 table 连接的 Fetch 默认情况下是 Eager(没有将其更改为 Lazy)。

日志文件中也没有 sql 语法错误。我错过了什么吗?

更新: 这是因为第二次加入,即 user2 返回 null,所以我没有得到任何数据。现在,如果有人能告诉我如何解决这个问题,查询应该是独立的,它不应该依赖于数据。

如果你想要 return 结果而不管依赖项中是否存在数据,那么你应该使用左连接而不是内连接(连接获取等于内连接获取):

"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";

现在,当 OneChat 对数据库没有任何 user2 依赖性时,无论如何查询仍会 return 结果。

就在旁边..如果你使用前缀,那么为了清楚起见,请尝试将前缀添加到 where 子句中的 group_idroot_chat_id 字段。