【问题标题】:How to store Key-Value pairs using JDO (datanucleus & appengine)如何使用 JDO 存储键值对(datanucleus & appengine)
【发布时间】:2012-06-15 13:55:42
【问题描述】:

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

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 数据库测试应用程序时,没有任何问题。

感谢您的任何建议!

【问题讨论】:

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


    【解决方案1】:

    只需更改您的主键定义:

    @PrimaryKey
    @Persistent
    private Integer id;
    

    收件人:

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

    会起作用的。

    【讨论】:

    • 非常感谢,它成功了!有趣的是,我尝试了一次 valueStrategy ,另一次尝试了 Long ,但不是同时使用两者!奇怪的是它需要 Long,尤其是当我真的不需要超过 20 亿个属性时! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多