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

时间:2017-10-17 13:02:39

标签: 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;
}

我想制作" news_paper_id"自动递增。我该怎么做?

3 个答案:

答案 0 :(得分:21)

我找到了解决这个问题的另一种方法,因为根据我的知识,在一些R& D之后,我们不能在复合主键中拥有自动增量属性。所以我在这里使用了索引和唯一约束,因为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;
}

答案 1 :(得分:4)

Priyanka Alachiya 的答案是正确的,但我需要在Kotlin进行采样...

对于Kotlin:

if let array = dictionary["array"] as? [String] {
    print(array, array.isEmpty)
}
if let string = dictionary["string"] as? String {
    print(string, string.isEmpty)
}

Here Kotlin solution

答案 2 :(得分:-1)

您可以将 Integer 类型用于news_paper_id,然后设置news_paper_id

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

 @PrimaryKey(autoGenerate = true)
private Integer news_paper_id;

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

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