【问题标题】:How to save protocol buffer classes directly using GreenDao如何使用 GreenDao 直接保存协议缓冲区类
【发布时间】:2014-01-28 04:01:22
【问题描述】:

GreenDao 提供了一个addProtobufEntity 方法让你直接持久化protobuf 对象。不幸的是,我找不到太多解释如何使用此功能的文档。

假设我正在尝试将外键添加到我的消息实体中,以便我可以访问其 PBSender protobuf 实体。这是我的生成器代码:

// Define the protobuf entity
Entity pbSender = schema.addProtobufEntity(PBSender.class.getSimpleName());
pbSender.addIdProperty().autoincrement();

// Set up a foreign key in the message entity to its pbSender
Property pbSenderFK = message.addLongProperty("pbSenderFK").getProperty();
message.addToOne(pbSender, pbSenderFK, "pbSender");

不幸的是,生成的代码无法编译,因为它试图访问我的 PBSender 类上不存在的 getId() 方法:

public void setPbSender(PBSender pbSender) {
    synchronized (this) {
        this.pbSender = pbSender;
        pbSenderID = pbSender == null ? null : pbSender.getId();
        pbSender__resolvedKey = pbSenderID;
    }
}

谁能解释一下应该如何管理与协议缓冲区实体的关系?

GreenDao 目前只支持 Long 主键。我的 protobuf 对象是否需要一种方法来返回唯一的 Long ID 以用作主键?

如果我删除我的自动增量 ID,则生成步骤将失败并出现以下错误:

java.lang.RuntimeException: Currently only single FK columns are supported: ToOne 'pbSender' from Message to PBSender

【问题讨论】:

  • 对不起,我没有使用greendao的经验。
  • 你悬赏的目的是什么?您的回答已经描述了实际状态和限制。你想要 greendao 的扩展吗?
  • 我在发布答案之前添加了赏金。我只是希望引起对这个问题的更多关注,但如果有人能提供更好的答案或提供 greenDAO 扩展,那就太棒了!

标签: android orm protocol-buffers foreign-key-relationship greendao


【解决方案1】:

greenDAO generator Entity source code 表明它目前不支持与协议缓冲区实体的关系:

public ToMany addToMany(Property[] sourceProperties, Entity target, Property[] targetProperties) {
    if (protobuf) {
        throw new IllegalStateException("Protobuf entities do not support realtions, currently");
    }

    ToMany toMany = new ToMany(schema, this, sourceProperties, target, targetProperties);
    toManyRelations.add(toMany);
    target.incomingToManyRelations.add(toMany);
    return toMany;
}

/**
 * Adds a to-one relationship to the given target entity using the given given foreign key property (which belongs
 * to this entity).
 */
public ToOne addToOne(Entity target, Property fkProperty) {
    if (protobuf) {
        throw new IllegalStateException("Protobuf entities do not support realtions, currently");
    }

    Property[] fkProperties = {fkProperty};
    ToOne toOne = new ToOne(schema, this, target, fkProperties, true);
    toOneRelations.add(toOne);
    return toOne;
}

但是,如果您的 Protobuf 类包含唯一的长 ID 和返回该 ID 的 public Long getId() 方法,我怀疑您可以完成这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多