JPA和谷歌应用程序引擎中的多对多关系
我有实体A和B,A可以有B的集合。B的同一个实例可以属于多个A。所以这里存在经典的多对多关系。
在 GAE 中,不直接支持多对多关系,而是提供使用键集来实现相关关系的能力。因此,在 AI 中,将在 B 中维护一组记录键。
现在的问题是 - 我如何查询属于给定类型 A 对象并匹配某些条件的类型 B 的对象?在普通 SQL 中,我会这样做:
select B.*
from
B inner join A
on B.A_ID=A.ID
where B.property0=criteria1
and B.property1=criteria2 ...
and ...
但是因为我不能执行 JOIN,所以我需要执行类似的操作
select B.*
from B
where B.A_ID in ( ... )
and B.property0=criteria1
and B.property1=criteria2 ...
and ...
,这样查询本身可能会因为 ID 的数量而变得很长。
还有更好的办法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果重构关系映射,您可以获得更好的查询。不要在 A 中存储一组键,而是在 B 中存储一组键。然后您可以使用 进行查询。
这样您就可以避免
in
运算符创建的多个查询。另外,请注意:
in
仅适用于 30 个或更少元素的列表。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
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.