3

GreenDao提供了一个addProtobufEntity方法来让您直接保持protobuf对象。不幸的是我找不到很多文件解释如何使用这个功能。如何使用GreenDao直接保存协议缓冲区类

假设我正在尝试将外键添加到Message实体中,以便可以访问其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

+0

对不起,但我没有使用greendao的经验。 – CommonsWare

+0

你给了什么赏金?您的回答已经描述了实际状态和限制。你想为greendao扩展吗? – AlexS

+0

我在发布我的答案之前添加了赏金。我只是希望更多地关注这个问题,但如果有人能够提供更好的答案或提供greenDAO扩展,那将是非常棒的! –

回答

2

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和一个public Long getId()方法来返回这个ID,我怀疑你可以做这个工作。