Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 505
Priyanka Alachiya Avatar asked Oct 17 '17 13:10

Priyanka Alachiya


People also ask

Do primary keys need to auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Is surrogate key auto increment?

Auto-incremented key, also called as surrogate key is a single table column which contains unique numeric values which can be used to uniquely identify a single row of data in a table.

Should I use auto increment ID?

Auto-increment should be used as a unique key when no unique key already exists about the items you are modelling. So for Elements you could use the Atomic Number or Books the ISBN number.


1 Answers

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; } 
like image 174
Priyanka Alachiya Avatar answered Sep 20 '22 12:09

Priyanka Alachiya