Android GreenDAO会生成额外的ID属性

时间:2014-06-18 14:32:01

标签: android database sqlite greendao

这是我的架构生成代码:

    Schema schema = new Schema(VERSION, "com.example.dao");

    Entity player = schema.addEntity("Player");
    Property playerIdProperty = player.addStringProperty("id").primaryKey().getProperty();
    player.addStringProperty("name").notNull();
    player.addStringProperty("created_at");
    player.addStringProperty("updated_at");

    Entity match = schema.addEntity("Match");
    match.addStringProperty("id").primaryKey();
    match.addIntProperty("score1");
    match.addIntProperty("score2");
    match.addStringProperty("created_at");
    match.addStringProperty("updated_at");

    match.addToOne(player, playerIdProperty, "dp1");
    match.addToOne(player, playerIdProperty, "dp2");
    match.addToOne(player, playerIdProperty, "op1");
    match.addToOne(player, playerIdProperty, "op2");


    new DaoGenerator().generateAll(schema, "app/src-gen");

这就是它产生的结果:

public class MatchDao extends AbstractDao<Match, String> {

public static final String TABLENAME = "MATCH";

/**
 * Properties of entity Match.<br/>
 * Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
    public final static Property Id = new Property(0, String.class, "id", true, "ID");
    public final static Property Score1 = new Property(1, Integer.class, "score1", false, "SCORE1");
    public final static Property Score2 = new Property(2, Integer.class, "score2", false, "SCORE2");
    public final static Property Created_at = new Property(3, String.class, "created_at", false, "CREATED_AT");
    public final static Property Updated_at = new Property(4, String.class, "updated_at", false, "UPDATED_AT");
    public final static Property Id = new Property(5, String.class, "id", true, "ID");
};

如您所见,在MatchDao中有两个名为“Id”的属性。我需要做的是生成两个表,主键是字符串(字符串是远程数据库的要求)和4个外键(每个匹配有4个播放器)。

问题是:为什么“Id”属性是重复的以及如何避免它?提前致谢

3 个答案:

答案 0 :(得分:4)

我犯了和你一样的错误。 目前您正在执行以下操作:

Entity player = schema.addEntity("Player");
Property playerIdProperty = player.addStringProperty("id").primaryKey().getProperty();
...
match.addToOne(player, playerIdProperty, "dp1");

但是你必须将playerId属性添加到目标类:

Entity player = schema.addEntity("Player");
player.addStringProperty("id").primaryKey();
...
Entity match = schema.addEntity("Match");
Property player1IdProperty = match.addLongProperty("dp1").getProperty();
...
match.addToOne(player, player1IdProperty);

希望这有帮助!

答案 1 :(得分:0)

我不确定但这个id属性不重复。此“id”属性是与实体“Player”的1:1关系产生的。也许addToOne(Entity target, Property fkProperty, java.lang.String name)方法存在一个错误。

答案 2 :(得分:0)

也许addToOne函数需要一个整数属性? 我建议你按照以下步骤操作:

  • 更改主键。这也是外键:

    Property playerIdProperty = player.addIdProperty().autoincrement().primaryKey().getProperty();`
    
  • 创建唯一的字符串标识符:

    player.addStringProperty("identifier").notNull().unique();
    

有了这个,你仍然有两个属性,但我认为模型更好。我赞成使用数字ID。抱歉我的英文。