开发者

How to get entry from datastore by position it was added? (Google app engine and JDO)

Here is my example:

Add new entry to datastore //position 1

Add new entry to datastore //position 2

Add new entry to datastore //position 3

Now i want to get entry, that was added at position 2. How it can be done with google app engine and JDO?

Looks for me that one way is to give PrimaryKey as Long ID and then use getObjectById. So Long ID will be equal to storing position automatically by the datastore.

Code t开发者_运维问答hat shows it:

import javax.jdo.annotations.*;
import javax.jdo.PersistenceManager;
import mypackage.PMF

public class Entry {
  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  private Long ID;

  //.. other fields
}


// create entries (suppose datastore is empty and i don't need deletes in future)
PersistenceManager pm = PMF.get().getPersistenceManager()
for(int i=0; i<10; i++){
  pm.makePersistent(new Entry());
}
// created entries have their IDs exaclty = 1,2,3,4,5,6,7,8,9,10 ?

// fetch entry, that was added second
Key entryKey = KeyFactory.createKey(Entry.class.getSimpleName(), 2L);
Entry secondEntry = pm.getObjectById(Entry.class, entryKey);  

Can i be sure that Long ID field will be always incremented by 1 for new entry and it will equal 1 for first? Or there is another better way? :)


This notion of "position" isn't an App Engine concept. App Engine makes no guarantee that system-generated IDs will be assigned sequentially with no gaps.

See http://code.google.com/appengine/docs/java/datastore/entities.html#Kinds_IDs_and_Names

You can take over ID assignment yourself, if you're careful, but, depending on your app and its usage pattern, creating your own ids introduces a bottleneck that'll limit your ability to create new entities quickly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜