我有实体 A 和 B,A 可以有 B 的集合。B 的同一个实例可以属于多个 A。所以这里存在经典的多对多关系。
在 GAE 中,不直接支持多对多关系,相反,它们提供了使用键集来建立相关关系的能力。因此,在 A 中,我将在 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 ...
但是因为我不能加入所以我需要做一些类似的事情
select B.*
from B
where B.A_ID in ( ... )
and B.property0=criteria1
and B.property1=criteria2 ...
and ...
因此,由于 ID 的数量,查询本身可能会很长。
有没有更好的方法?
最佳答案
如果重构关系映射,您可以获得更好的查询。不是在 A 中存储一组键,而是在 B 中存储一组键。然后您可以查询
select * from B where a_id = {idOfRelevantA} and property0 = {criterion0} and property1 = {criterion1}...
这样您就可以避免 in
运算符创建的多个查询。
另外,请注意:in
仅适用于 30 个或更少元素的列表。
关于java - JPA 和 google app engine 中的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8036420/