Can I persist child objects in @PrePersist handler

2019-09-15 02:47发布

I am new to Objectify and trying to implement One-to-Many relationship. I have entities Organization and entity Person. Organization has @Transient property List< Person > contactPeople. Class Person has @Parent property Key< Organization > organizationKey which I can set via setter.

I'd like to persist contactPeople in @PrePersist handler of Organization. In order to do that I need to set parent key in Person.

Wiki here says: "You can't update @Id or @Parent fields in a @PrePersist callback; by this time, the low-level Entity has already been constructed with a complete Key so it can be passed in as an optional parameter."

I'm not sure this is still accurate information ? Because key of com.google.appengine.api.datastore.Entity object that I get in PrePersist handler has key that literally says "no-id-yet".

How would you implement this ?

Thank you!

Update at Nov 17, 2011:

In new Objectify4 we'll be able to do semi-automatic relationships like this:

class Beastie {
   @Parent
   @Load
   ParentThing parent;

   @Id Long id;

   @Load({"bigGroup", "smallGroup"})
   SomeThing some;

   @Load("bigGroup")
   List<OtherThing> others;

   @Load
   Ref<OtherThing> refToOtherThing;

   Ref<OtherThing> anotherRef;  // this one is never fetched automatically
}

Here is evolving design document of new version.

This is big news. Twig author, John Patterson, joined Objectify project today.

1条回答
Bombasti
2楼-- · 2019-09-15 03:31

Hm, seems that you need to make an Dao in front of your data models. So, you will able to do something like:

Organization organization = ...
List<Person> people = ...
ob.put(organization)
for (Person person: people) {
    person.organizationKey = organization.getKey();
    ob.put(person);
    organization.contactPeopleKeys.add(person.getKey());
}
ob.put(organization)

GAE+Objectify requires a lot of thing to handle by your own code, so it's a common thing

查看更多
登录 后发表回答