Eti
Eti

Reputation: 257

How to store Key-Value pairs using JDO (datanucleus & appengine)

I have defined a ConfigurationProperty class, which is basicly a key-value pair (with key being a strictly positive integer and value being a string):

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(detachable = "true")
public final class ConfigurationProperty
{
    @PrimaryKey
    @Persistent
    private Integer id;

    @Persistent
    private String value;

    public ConfigurationProperty(Integer id, String value)
    {
        this.id = id;
        this.setValue(value);
    }

    public Integer getId()
    {
        return this.id;
    }

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
}

As you can see, I'm defining a field "id" (which is the key of the key-value pair) and use it as the class's primary key.

However, when I try to access an entry:

int searchId = 4;
ConfigurationProperty property =
        this.persistence.getObjectById(ConfigurationProperty.class, searchId);

I get the exception:

javax.jdo.JDOFatalUserException: Received a request to find an object of type [mypackage].ConfigurationProperty identified by 4.  This is not a valid representation of a primary key for an instance of [mypackage].ConfigurationProperty.

NestedThrowables:
org.datanucleus.exceptions.NucleusFatalUserException: Received a request to find an object of type [mypackage].ConfigurationProperty identified by 4.  This is not a valid representation of a primary key for an instance of [mypackage].ConfigurationProperty.)

I'm almost sure I would not run into an exception should I create a separate field for the primary key and the pair's key, but that would create some form of redundancy and possibly performance issues, since the pair's key is unique.

I also only get the exception on Google Appengine. When I tested the application using a Derby database, there were no problems.

Thank you for any suggestion!

Upvotes: 1

Views: 685

Answers (1)

alexey28
alexey28

Reputation: 5220

Just change your primary key definition from:

@PrimaryKey
@Persistent
private Integer id;

To:

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;

Will work.

Upvotes: 3

Related Questions