Get an Objectify Entity's Key

此生再无相见时 提交于 2019-12-01 01:31:06

问题


Dummy question.

I create my POJO Objectify entity (for example, "Category") and persist it.

Then I retrieve it via a query.

I want to use it in a one-to-may relationship e.g. want to set my category to one or more "Products".

I will have this in my "Product"'s code: Key<Categoria> categoria;

So the question is: how can I find my retrieved entity's key for setting it in my product?


回答1:


I'm usually adding an extra method:

@Transient
Key<Categoria> getKey() {
   return Key.create(Categoria.class, id);
}

and use it where it needed:

anCategoria.getKey()



回答2:


For objectify 4 use:

public Key<Foo> getKey() {
   return Key.create(Foo.class, id);
}

Or if the entity has a @Parent

public Key<Bar> getKey() {
   return Key.create(parentKey, Bar.class, id);
}



回答3:


The Key class in Objectify 4 has this method:

public static <T> Key<T> create(T pojo)

so, if you already have read the entity (called category in this example) from the datastore, you can just call

product.categoria = Key.create(category);


来源:https://stackoverflow.com/questions/7162141/get-an-objectify-entitys-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!