【问题标题】:Get an Objectify Entity's Key获取 Objectify 实体的密钥
【发布时间】:2011-11-01 23:48:47
【问题描述】:

虚拟问题。

我创建了我的 POJO Objectify 实体(例如,“Category”)并将其持久化。

然后我通过查询检索它。

我想在一对一的关系中使用它,例如想将我的类别设置为一个或多个“产品”。

我将在我的“产品”代码中包含这个:Key<Categoria> categoria;

所以问题是:如何找到检索到的实体的密钥以在我的产品中设置它?

【问题讨论】:

    标签: google-app-engine key objectify


    【解决方案1】:

    对于objectify 4使用:

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

    或者如果实体有@Parent

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

    【讨论】:

    • 用户应注意,如果定义了@Parent,则必须使用父键来生成 Bar 键。
    • 有没有办法在不为每个实体编写新代码的情况下获取密钥?
    【解决方案2】:

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

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

    并在需要的地方使用它:

    anCategoria.getKey()
    

    【讨论】:

    • 在 Objectify 4 中它给了我一个错误:构造函数不可见。
    • Key.create(Categoria.class, id) - 比构造函数稍微方便一些。
    【解决方案3】:

    Objectify 4 中的 Key 类有这个方法:

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

    所以,如果您已经从数据存储区读取了实体(在此示例中称为 category),则只需调用

    product.categoria = Key.create(category);
    

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多