Getting Entity Key with Objectify 4

偶尔善良 提交于 2019-12-07 11:55:05

问题


I need to do getKey() with this kind of Entity:

@Entity
public class Value {
    @Id
    private long id;
    private byte[] value;

    com.googlecode.objectify.Key<Value> getKey() {
        return com.googlecode.objectify.Key.create(Value.class, id); // When executed this line throws NullPointerException
    }

        // Code omitted
}

However the pattern I used before with version 3 seems to be not applicable anymore. The @Transient is replaced by @Ignore but when I annotate my getKey() function with @Ignore I get this error:

The annotation `@Ignore` is disallowed for this location 

So I just commented it out. And see if it will work.

Furthermore,

When I run my application the getKey() function throws NullPointerException as commented above.

So, what is the pattern to get a @Entity key?


回答1:


You can't create a Key with a null or 0 id. Neither Objectify nor the datastore will allow it.

If you want to create a Key from an entity, make sure it has a valid id first.




回答2:


Annotation @Ignore is targeted only for the fields of an entity in order to declare that these fileds will not be store in the datastore. Since, getKey() is a method, you shouldn't use @Ignore annotation on that.

For more info about the @Ignore annotation take a look at: http://objectify-appengine.googlecode.com/git/javadoc/index.html

Hope this helps!

Update:

For the NPE, not really sure what is the problem. You can try replacing your method with this one and see if it works.

com.googlecode.objectify.Key<Value> getKey() {
    return new com.googlecode.objectify.Key<Value>(Value.class, id); 
}


来源:https://stackoverflow.com/questions/12830906/getting-entity-key-with-objectify-4

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