如何使用JDO存储键值对(datanucleus& appengine)

时间:2012-06-15 13:55:43

标签: java google-app-engine primary-key jdo datanucleus

我已经定义了一个ConfigurationProperty类,它基本上是一个键值对(键是一个严格正整数,值是一个字符串):

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;
    }
}

正如您所看到的,我正在定义一个字段“id”(这是键值对的键)并将其用作类的主键。

但是,当我尝试访问条目时:

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

我得到例外:

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.)

我几乎可以肯定,如果我为主键和对的密钥创建一个单独的字段,我就不会遇到异常,但这会产生某种形式的冗余和可能的性能问题,因为该对的密钥 唯一。

我也只在Google Appengine上获得例外。当我使用Derby数据库测试应用程序时,没有任何问题。

感谢您的任何建议!

1 个答案:

答案 0 :(得分:3)

只需更改主键定义:

@PrimaryKey
@Persistent
private Integer id;

要:

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

会工作。