获得客观实体的关键

Fab*_* B. 7 google-app-engine key objectify

假的问题.

我创建了我的POJO Objectify实体(例如,"Category")并坚持下去.

然后我通过查询检索它.

我想以一对一的关系使用它,例如想要将我的类别设置为一个或多个"产品".

我将在我的"产品"代码中有这个: Key<Categoria> categoria;

所以问题是:我怎样才能找到我检索到的实体在我的产品中设置它的关键?

小智 13

对于物体化4使用:

public Key<Foo> getKey() {
   return Key.create(Foo.class, id);
}
Run Code Online (Sandbox Code Playgroud)

或者,如果实体具有@Parent

public Key<Bar> getKey() {
   return Key.create(parentKey, Bar.class, id);
}
Run Code Online (Sandbox Code Playgroud)


Igo*_*nov 10

我通常会添加一个额外的方法:

@Transient
Key<Categoria> getKey() {
   return Key.create(Categoria.class, id);
}
Run Code Online (Sandbox Code Playgroud)

并在需要的地方使用它:

anCategoria.getKey()
Run Code Online (Sandbox Code Playgroud)

  • 在Objectify 4中,它给了我一个错误:该构造函数不可见. (3认同)
  • `Key.create(Categoria.class,id)` - 比构造函数稍微方便一些. (2认同)