【问题标题】:GreenDao primary key on multiple columns多列上的GreenDao主键
【发布时间】:2016-11-21 17:31:55
【问题描述】:

我正在使用 greendao 在 Android 上维护 SQL 数据库。现在我面临一个生成具有两列作为主键的实体的问题。需要明确的是,我的 column1 和 column2 都是 Long 值,它们共同构成一个主键。

我尝试将其建模为

@Index(unique = true)
private Long column1, column2

但它不起作用。我在尝试插入时遇到唯一约束失败,在尝试插入或替换时,它只是根据 column1 id 替换。

【问题讨论】:

    标签: android greendao


    【解决方案1】:

    我已经通过定义这样的实体来解决它:

    @Id(autoincrement = true) //I totally don't care about value of this field
    private Long idLocal;
    
    @Index //this are 2 columns that I use as primary key
    private Long column1id, column2id;
    

    我知道这可能不是最佳解决方案,但它确实有效。但是赏金仍然开放,我会将其提供给任何能给我更好的解决方案的人。

    【讨论】:

      【解决方案2】:

      GreenDao 不支持您所期望的复合主键。

      Issue 26 已在 github 项目上就此打开,Issue 476 也引用了它。

      您可以尝试通过为引用其他属性的主键设置一个 ID 来解决此问题,但这不允许您对字段设置唯一限制,因此您必须自己验证。

      另见http://greenrobot.org/greendao/documentation/modelling-entities/#Primary_key_restrictions

      【讨论】:

      • 我可以通过执行以下操作向字段添加唯一约束。例如,我们希望customer 表对名字和姓氏字段都具有唯一限制(在实践中不好,但只是一个示例),您将信息放在@Entity 注释(GreenDao 3)中,如下所示:@Entity(nameInDb = "customer",indexes = { @Index(value = "firstname,lastname", unique = true)})
      • 这是迄今为止最好的解决方案,而且效果很好。 Greendao 实体建模也是如此。 greenrobot.org/greendao/documentation/modelling-entities/…
      猜你喜欢
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      相关资源
      最近更新 更多