为什么这个按ob的客观化查询不会返回结果

时间:2014-02-22 07:53:54

标签: objectify

我发布了孔jsf方法,但重要的一行只是: 食物食品= ofy()。load()。type(Food.class).id(lng).now();

public StreamedContent getImage() {
        if (getFacesContext().getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            return new DefaultStreamedContent(); // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
        }
        String foodId = (String) getRequest().getParameter("foodId");
        Long lng = Long.parseLong(foodId);
        log.warning("GET image for Food ID: "+lng);
        Food food = ofy().load().type(Food.class).id(lng).now();
        return new DefaultStreamedContent(new ByteArrayInputStream(food.getImage()), "image/jpeg");
    }

实体食品:

@Entity
public class Food implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id Long id;
    @Parent @Load Key<TableParent> owner;
    @Index String name;
    String description;
    byte[] image;
    @Load Ref<Category> category;

    public Food () {
    }

是。它有父,但我不在这里发布,因为这个父不应该用于ID的简单查询。我确定id存在,并且确实没有看到返回的原因总是为null。它可以保持一致性,但我在同一个项目上一遍又一遍地进行这种查询。使用相同的localy并部署到谷歌应用引擎 - 总是为存在数小时的对象返回null。

2 个答案:

答案 0 :(得分:3)

如果没有父级,则无法访问具有父级的实体。我不能仅通过Id访问实体,因为可能有其他实体具有相同的ID但是其他父实体。所以在这样的查询中使用parent是必须的:

Food food = ofy().cache(false).load().key(Key.create(Key.create(TableParent.class, parent.getId()), Food.class, lng)).now();

这可以完成工作

答案 1 :(得分:2)

除非您明确创建一个复制了id值的单独索引字段,否则无法通过GAE中的id进行查询。但请记住,id在父作用域中是唯一的,因此它可能无法达到您想要的效果。

Objectify的load-by-id是按键加载操作。你的例子:

ofy().load().type(Food.class).id(lng).now();

只是一个快捷方式:

ofy().load().key(Key.create(Food.class, lng)).now();

现在您可以看到为什么还需要添加.parent()调用。

相关问题