JPA and many-to-many relations in google app engine

与世无争的帅哥 提交于 2019-12-20 03:03:33

问题


I have entities A and B, and A can have set of B. The same instance of B can belong to several A. So there is classical many-to-many relation here.

In GAE there is no direct support of many-to-many relations, instead they're offering an ability to use sets of keys for related relations. So in A I will maintain set of keys of records in B.

Now the problem is - how can I query for objects of type B belonging to given object of type A and matching certain criteria? In plain SQL I would do that like:

select B.* 
from 
    B inner join A 
        on B.A_ID=A.ID 
where B.property0=criteria1 
      and B.property1=criteria2 ...
      and ...

but because I can not do JOIN then I need to do something like

select B.* 
from B 
where B.A_ID in ( ... ) 
      and B.property0=criteria1 
      and B.property1=criteria2 ...
      and ...

so the query itself can be very long because of amount of IDs.

Is there any better way?


回答1:


If you refactor your relationship mapping you can get a better query. Instead of storing a set of keys in A, store a set of keys in B. Then you can query with

select * from B where a_id = {idOfRelevantA} and property0 = {criterion0} and property1 = {criterion1}...

This way you avoid the multiple queries that the in operator creates.

Also, beware: in will only work for a list of 30 elements or fewer.



来源:https://stackoverflow.com/questions/8036420/jpa-and-many-to-many-relations-in-google-app-engine

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