How to make Primary key Auto increment while using Composite Primary keys in Room persistent library?

丶灬走出姿态 提交于 2019-11-30 06:31:16

问题


I am using Room persistent library. I have requirement to add two primary keys in one table and one of the primary key should be auto increment. I don't know exact syntax to achieve this. Below is my Model class:

@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;
}

I want to make "news_paper_id" to be auto incremented. How can i make it?


回答1:


I found another way around for this problem because as per my knowledge after some R&D, we can not have auto increment property in Composite Primary keys. So I used indices and unique constraint here because Room does not have direct UNIQUE constraint till now. So below is my working code:

@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;
}



回答2:


you can use Integer type to news_paper_id and so set 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;
}


来源:https://stackoverflow.com/questions/46790830/how-to-make-primary-key-auto-increment-while-using-composite-primary-keys-in-roo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!