JPQL multiple left join with one class

孤者浪人 提交于 2019-12-11 05:16:10

问题


I have following problem with JPQL: One Class has three fields:

public class Message{
  Integer ownerId;
  Integer fromUserId;
  Integer toUserId;
  //rest of implementation
}

then I want to search in the database by the user names, but we have 3 users attached to this Message: Owner, Recipient and Sender, so what I did in SQL is:

SELECT * FROM message m 
LEFT JOIN user o ON m.owner_id=o.id 
LEFT JOIN user fu ON m.from_user_id = fu.id
LEFT JOIN user tu ON m.to_user_id = tu.id
WHERE o.name like '%foo%' OR fu.name like '%foo%' OR tu.name like '%foo%';

Which is maybe not the fastest query, but works fine. Then I wanted to translate it to JPQL, but it's not easy. I get exception on 'on' token, I understand that JOIN is possible if the class has relation defined to another class, but here the relation is a bit complicated as we have 3 users related to one Message. Any ideas how to solve this?


回答1:


I think this should do the trick:

FROM message m                -- SELECT * is optional in JPQL
LEFT JOIN m.owner o           -- In JPQL, you put the path to the related object
LEFT JOIN m.from_user_id fu   -- and JPA does the rest using the mappings
LEFT JOIN m.to_user_id tu
WHERE o.name like '%foo%' OR fu.name like '%foo%' OR tu.name like '%foo%';

The thing to remember is that in JPQL the JOIN conditions are defined in the mappings, so you don't specify them in the queries: just put the path to the object you want to reference and JPA will infer the rest from the mappings.



来源:https://stackoverflow.com/questions/12498949/jpql-multiple-left-join-with-one-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!