我正在尝试通过列表属性对我的 Java 应用程序引擎对象进行建模,以实现快速高效的查询。我可以改进这段代码吗?
我真的不想迁移到 Objectify。
这是检索它的代码:
query = persistenceManager.newQuery(HuddleCreatorIndex.class, ":p.contains(creator)");
List<HuddleCreatorIndex> myCreatorIndexList = (List<HuddleCreatorIndex>) query.execute(KeyFactory.createKey(Contact.class.getSimpleName(), fbUserId));
if (myCreatorIndexList.size() > 0) {
Set<Long> huddles = myCreatorIndexList.get(0).getHuddles();
//THIS FOR LOOP DID THE TRICK, why is this necessary? Never saw it in any examples
for (Long huddleKey : huddles)
alist.add(persistenceManager.newObjectIdInstance(Huddle.class, huddleKey));
Collection<Huddle> huddlesICreated = persistenceManager.getObjectsById(huddles);
allMyHuddles.addAll(huddlesICreated);
}
以下是显示对象最初存储方式的其余支持代码,以及相关的模型类。
此代码在创建 Huddle 时调用(这会正确设置数据存储中的所有对象)
txn.begin();
//First, create the Huddle, this main model class
newHuddle.setInvitees(inviteeList);
newHuddle = pm.makePersistent(newHuddle);
huddleId = newHuddle.getId();
//Now create the first index
HuddleIndex newIndex = new HuddleIndex();
newIndex.setParent(KeyFactory.createKey(Huddle.class.getSimpleName(), newHuddle.getId()));
newIndex.setInvitees(inviteeList);
pm.makePersistent(newIndex);
//And finally, create the other index
Query query = pm.newQuery(HuddleCreatorIndex.class);
query.setFilter(":p.contains(creator)");
List<HuddleCreatorIndex> list = (List<HuddleCreatorIndex>) query.execute(creator.getId());
if (list != null && list.size() > 0) {
HuddleCreatorIndex thisIndex = list.get(0);
Set<Key> huddles = thisIndex.getHuddles();
huddles.add(KeyFactory.createKey(Huddle.class.getSimpleName(), newHuddle.getId()));
thisIndex.setHuddles(huddles);
} else {
HuddleCreatorIndex newCreatorIndex = new HuddleCreatorIndex();
newCreatorIndex.setCreator(creator.getId());
Set<Long> huddleSet = new HashSet<Long>(1);
huddleSet.add(newHuddle.getId());
newCreatorIndex.setHuddles(huddleSet);
pm.makePersistent(newCreatorIndex);
}
txn.commit();
这是我的实际模型对象与真实数据
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class Huddle {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
private Key creator;
private String name;
private Date whenTimeStamp;
private Date creationTimeStamp;
private String userIdType;
private Set<Key> invitees;
private String status;
private Set<Key> choices;
private List<Vote> votes;
//setters, getters, and constructor omitted
}
我的索引对象使列表属性魔术发生
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class HuddleCreatorIndex {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key id;
private Key creator;
private Set<Long> huddles;
//setters, getters, and constructor omitted
}