Reputation: 79
I have a question and I didn't find what I wanted to do. I'm using google Endpoints with appengine and Objectify. I have an entity Round which need the key of an entity Game just created. So when I have to create a new Game I create my new game and after that I create the round with the new key. I use the function .now() to save the game but sometimes the game is not created and I have a Round created without any Game. Because it was problematic I decided to loop to get the game until it's created, but I know it's a very bad way to do it and I am wondering what I can use instead.
Before :
//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();
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();
Thanks for your help.
Upvotes: 0
Views: 834
Reputation: 7543
Why load the saved 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();
If your intention was to make sure that saving the game was successful before moving on, use a transaction:
Either all of the operations in the transaction are applied, or none of them are applied.
Objectify transaction docs with examples.
Upvotes: 1