Getting Entity Key with Objectify 4

2019-05-10 14:12发布

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?

2条回答
Lonely孤独者°
2楼-- · 2019-05-10 14:37

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.

查看更多
forever°为你锁心
3楼-- · 2019-05-10 14:41

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); 
}
查看更多
登录 后发表回答