【问题标题】:How to make Primary key Auto increment while using Composite Primary keys in Room persistent library?如何在 Room 持久库中使用复合主键时使主键自动递增?
【发布时间】:2018-03-29 04:27:21
【问题描述】:

我正在使用 Room 持久库。我需要在一个表中添加两个主键,其中一个主键应该是自动递增的。我不知道实现这一点的确切语法。下面是我的模型类:

@Entity(tableName = "newsPapers", primaryKeys = 
{"news_paper_id","news_paper_name"})
public class SelectNewsModel {

private int news_paper_id;

@ColumnInfo(name = "image_url")
private String imageUrl;

@ColumnInfo(name = "news_paper_name")
private String newsPaperName;
}

我想让“news_paper_id”自动递增。我该怎么做呢?

【问题讨论】:

  • 为什么需要两个主键?如果两者相同?
  • @KuLdipPaTel 对不起,我不明白你的问题。我想要两个不一样的主键。一个是“news_paper_id”,另一个是“news_paper_name”。我希望“news_paper_id”自动递增!我希望这个解释能消除你的疑惑。

标签: android auto-increment composite-primary-key android-room


【解决方案1】:

Priyanka Alachiya 的答案是对的,但我需要 Kotlin 中的示例...

对于 Kotlin:

@Entity(tableName = "newsPapers", indices = arrayOf(Index(value = ["news_paper_name"], unique = true)))

Here Kotlin solution

【讨论】:

    【解决方案2】:

    我找到了解决这个问题的另一种方法,因为根据我的一些研发知识,我们不能在复合主键中拥有自动增量属性。所以我在这里使用了索引和唯一约束,因为到目前为止 Room 没有直接的 UNIQUE 约束。所以下面是我的工作代码:

    @Entity(tableName = "newsPapers", indices = {@Index(value = 
           {"news_paper_name"}, unique = true)})
    public class SelectNewsModel {
    
        @PrimaryKey(autoGenerate = true)
        private int news_paper_id;
    
        @ColumnInfo(name = "image_url")
        private String imageUrl;
    
        @ColumnInfo(name = "news_paper_name")
        private String newsPaperName;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 2020-01-29
      • 2015-06-08
      • 2017-10-21
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多