On 18 Mar 2010, at 20:27, Mark wrote:
Hi,
I'm not understanding how to implement a simple unowned relationship.
I have two classes like:
class Farm {
List<Key> mHorses;
}
class Horse {
@PrimaryKey
Key mKey;
}
so a Farm can have some horses. I'd like to create a new horse, then
put it on a farm, in one transaction.
This requires Horse to be a descendant of Farm to be in the same
entity group. Therefore a horse could not move farms unless you
delete and recreate it with a new Key.
But how do I know the key of the
horse during the transaction?:
Farm farm = loadFarm(...);
Horse horse = new Horse();
horse.setName("Roger");
try {
tx = pm.currentTransaction();
tx.begin();
pm.makePersistent(horse); // is the key available now?
farm.mHorses.add(horse.mKey);
pm.makePersistent(farm);
tx.commit();
}
when is the Horse.mKey value actually set and ready for use?
As soon as you "put" an entity in the datastore without a key a new
one will be generated with a unique long value. So you can use this
in the rest of the same transaction
Or do I
have to do this as two separate atomic operations:
1) Save the horse which generates its mKey value.
2) If that worked, add it to the farm, persist the farm again.
3) If that worked, all good, if not, have to delete the horse cause
now it's in limbo?
You won't need to delete any horses if it is done in a transaction -
rollback will take care of everything.
I know you are experimenting with JDO but just as an example in Twig
to show how much cleaner it is without messing with Keys:
class Farm {
List<Horse> mHorses; // direct unowned reference
}
class Horse {
String name;
}
No Keys are needed so your data models are actually more portable and
natural than using JDO-GAE.
Then to store a horse with the Farm as its parent go:
farm.mHorses.add(myHorse);
datastore.store(myHorse, myFarm);
datastore.update(myFarm);
The store() command creates the Key and caches it so when you update
the farm it already has the Key.
Hope some of this helps!
John
--
You received this message because you are subscribed to the Google Groups "Google
App Engine for Java" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-appengine-java?hl=en.