开发者

Java App Engine Get Auto Generated Key value

I have been trying to port a tomcat/mysql application over to Google App Engine. I am having a little hang up on getting key values of objects that I have just persisted. Is there a way to get t开发者_开发问答he Key value of the persisted object? Does anyone have an code in Java that can show how to do this?

Thanks, Eric


I think you'll need to post a code sample before we can tell you what you're doing wrong. I have an Entity with an id type of Long, and the id gets filled in after I call makePersistent(). Here is what the code looks like:

    GameEntity game = new GameEntity();
    log.warning("before makePersistent id is " + game.getId());
    pm.makePersistent(game);
    log.warning("after makePersistent id is " + game.getId());

Here is a snippet of the GameEntity class:

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class GameEntity {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

And the output shows what you'd expect:

WARNING 6428 - before makePersistent id is null
WARNING 6444 - after makePersistent id is 6

UPDATE: It occurred to me belatedly that you might want an actual Key object. You can create that yourself if you have the id:

public Key getKey() {
    return KeyFactory.createKey(GameEntity.class.getSimpleName(), id);
}


JPA or JDO or what?

Google app engine has good documents

http://code.google.com/appengine/docs/java/datastore/usingjpa.html


Not exactly answer, but...

Ids are apparently not assigned until you commit the transaction. I switched to generating random string ids for my GAE objects myself, before I save them.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜