我正在实现相同类型实体之间的友谊功能Profile
。此实体类型是根(非父)实体。Profile 有一个Set<Ref<Profile>>
名为friends
getter的字段getFriends()
。
这里的代码:
public boolean makeFriends(final Profile profile1, final Profile profile2) {
final Ref<Profile> profileRef1 = Ref.create(profile1);
final Ref<Profile> profileRef2 = Ref.create(profile2);
boolean result = false;
// test to avoid useless transaction
if (!profile1.getFriends().contains(profileRef2) && !profile2.getFriends().contains(profileRef1)) {
// add to friends (Set<Ref<Profile>>) the Ref of each other
result = ofy().transact(new Work<Boolean>() {
@Override
public Boolean run() {
profile1.getFriends().add(profileRef2);
profile2.getFriends().add(profileRef1);
ofy().save().entities(profile1, profile2).now();
return true;
}
});
}
return result;
}
这段代码给了我一个:
java.lang.IllegalArgumentException: cross-group transaction need to be explicitly specified, see TransactionOptions.Builder.withXG
即使 Objectify 文档说:
Objectify 不需要特殊标志来启用跨组事务。如果您在一个事务中访问多个实体组,则该事务为 XG 事务。如果您只访问一个,则不是。5 个 EG 的标准限制适用于所有交易。
那么,为什么我的交易失败了?
我的代码应该涉及两个实体组(每个一个Profile
),所以在 5 个限制之后。查看TransactionOptions.Builder.withXG
文档,我应该TransactionOptions.Builder.withXG(true);
在之前调用。此方法返回一个TransactionOptions
但我不知道传递它的方法!
提前致谢