我一直在尝试将 tomcat/mysql 应用程序移植到 Google App Engine。我有点挂断了获取我刚刚坚持的对象的关键值。有没有办法获取持久化对象的Key值?有没有人有可以说明如何执行此操作的 Java 代码?
谢谢, 埃里克
最佳答案
我认为您需要先发布代码示例,然后我们才能告诉您您做错了什么。我有一个 id 类型为 Long 的实体,在我调用 makePersistent()
后填充了 id。代码如下所示:
GameEntity game = new GameEntity();
log.warning("before makePersistent id is " + game.getId());
pm.makePersistent(game);
log.warning("after makePersistent id is " + game.getId());
这是 GameEntity 类的片段:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class GameEntity {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
输出显示了您所期望的:
WARNING 6428 - before makePersistent id is null
WARNING 6444 - after makePersistent id is 6
更新: 我后来才想到您可能需要一个实际的 Key 对象。如果你有 id,你可以自己创建:
public Key getKey() {
return KeyFactory.createKey(GameEntity.class.getSimpleName(), id);
}
关于Java App Engine 获取自动生成的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121643/