Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Objectify Entity's Key

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?

like image 351
Fabio B. Avatar asked Aug 23 '11 13:08

Fabio B.


3 Answers

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);
}
like image 177
alejandrogr Avatar answered Nov 08 '22 00:11

alejandrogr


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()
like image 45
Igor Artamonov Avatar answered Nov 08 '22 01:11

Igor Artamonov


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);
like image 21
TmTron Avatar answered Nov 08 '22 00:11

TmTron