a way to convert appengine datastore Entity to my object?

自闭症网瘾萝莉.ら 提交于 2019-12-07 04:11:12

问题


Using google appengine 1.3.0 w/ java and jdo...

While trying to write JDO querys for 1-to-many owned relationships, I came across a non-JDO concept that I thought was really smart. Ancestor Querys. The appengine.api.datastore.Query interface allows for scoping of a query using the parent Key.

Unfortunately the results from the query are 'Entity' objects with property lists. Is there a util in the apis that will convert one of these Entity objects into my JDO object or even a simple DTO bean (that matched my JDO object)?

I've taken a crack a brute forcing it with the code below but don't like the double lookup.

 PersistenceManager pm;
 DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();  
 List<MyObject> results;

 com.google.appengine.api.datastore.Query query = new Query( "MyObject", KeyFactory.stringToKey( parentId ) );
 query.addFilter("rank", Query.FilterOperator.GREATER_THAN_OR_EQUAL, minRank );
 query.addSort("rank");
 query.setKeysOnly();
 for (Entity anEntity : datastore.prepare(query).asIterable()) {
  results.add( pm.getObjectById( MyObject.class, anEntity.getKey() ) );
 }

回答1:


This is not the silver bullet I think you were looking for; it requires some grunt work to accomplish.

DAO code

DatastoreService datastore = DatastoreServiceFactory
 .getDatastoreService();
List<Foo> results = new ArrayList<Foo>();

Query query = new Query("Foo", KeyFactory.stringToKey(""));
List<Entity> entities = datastore.prepare(query).asList(
  FetchOptions.Builder.withDefaults());

for (Entity entity : entities) {
  results.add(new Foo(entity));
}

class Foo

public Foo(Entity entity) {
  // TODO get properties from entity and populate POJO
  this.bar=entity.getProperty("bar");
  //get the key
  //if the @PrimaryKey is a Long use this
  this.id=entity.getKey().getId();
  //if the @PrimaryKey is a String use this
  this.id=entity.getKey().getName();
}



回答2:


you can use org.datanucleus.store.appengine.JDODatastoreBridge.toJDOResult()



来源:https://stackoverflow.com/questions/2291028/a-way-to-convert-appengine-datastore-entity-to-my-object

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