Objectify:使用创建的实体键juste

时间:2014-01-29 18:05:14

标签: java google-app-engine entity google-cloud-endpoints objectify

我有一个问题而且我没有找到我想做的事情。我正在使用谷歌端点与appengine和Objectify。我有一个实体Round,它需要刚刚创建的实体游戏的密钥。因此,当我必须创建一个新游戏时,我创建了我的新游戏,之后我使用新密钥创建了一个回合。我使用函数.now()来保存游戏,但有时候游戏没有创建,我创建了一个没有任何游戏的Round。因为它有问题所以我决定循环来获取游戏,直到它被创建,但我知道这是一个非常糟糕的方法,我想知道我可以使用什么。

之前:

//Create a new game
Game game = new Game(pending_game.getPlayer(),pending_game.getApplicant());
ofy().save().entity(game).now();

//Get the player just created
game = ofy().load().type(Game.class).filter("player1 =", pending_game.getPlayer()).filter("player2 =", pending_game.getApplicant()).first().now();
Key<Game> key_game = Key.create(Game.class, game.getId());          
//We add the new round
Round round = new Round(key_game,generateWord());
ofy().save().entity(round).now();

现在:

//Create a new game
Game game = new Game(pending_game.getPlayer(),pending_game.getApplicant());
ofy().save().entity(game).now();

Key<Game> key_game = null;
//Get the player just created 
for(int i=0; i<5 && key_game == null;i++)
{
    //Get the key of the new game created
    game = ofy().load().type(Game.class).filter("player1 =", pending_game.getPlayer()).filter("player2 =", pending_game.getApplicant()).first().now();
    key_game = Key.create(Game.class, game.getId());
}                   
//We add the new round
Round round = new Round(key_game,generateWord());
ofy().save().entity(round).now();

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

为什么要加载已保存的game

Game game = new Game(pending_game.getPlayer(),pending_game.getApplicant());
ofy().save().entity(game).now();    
Key<Game> key_game = Key.create(Game.class, game.getId());          
//We add the new round
Round round = new Round(key_game,generateWord());
ofy().save().entity(round).now();

如果您打算在继续之前确保保存游戏成功,use a transaction

  

应用事务中的所有操作,或者不应用任何操作。

Objectify transaction docs以及示例。