如何在Room持久性库中使用复合主键时使主键自动递增?

Pri*_*iya 19 android auto-increment composite-primary-key android-room

我正在使用Room persistent library.我要求在一个表中添加两个主键,其中一个主键应该是自动增量.我不知道实现这一目的的确切语法.下面是我的Model类:

@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;
}
Run Code Online (Sandbox Code Playgroud)

我想让"news_paper_id"自动递增.我该怎么做?

Pri*_*iya 24

我找到了解决这个问题的另一种方法,因为根据我的知识,经过一些研发,我们不能在复合主键中拥有自动增量属性.所以我在这里使用了索引和唯一约束,因为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;
}
Run Code Online (Sandbox Code Playgroud)


小智 9

Priyanka Alachiya的答案是正确的,但我需要 Kotlin 中的样本...

对于科特林:

@Entity(tableName = "newsPapers", indices = arrayOf(Index(value = ["news_paper_name"], unique = true)))
Run Code Online (Sandbox Code Playgroud)

这里 Kotlin 解决方案