Priyanka Alachiya
Priyanka Alachiya

Reputation: 1726

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?

Upvotes: 30

Views: 14533

Answers (3)

mahdi tavakoli
mahdi tavakoli

Reputation: 21

in kotlin :

@Entity(
    tableName = "newsPapers",
    indices = [
        Index(value = ["news_paper_name"], unique = true)
    ]
)
data 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;
}

Upvotes: 2

Ivanov O.
Ivanov O.

Reputation: 159

Priyanka Alachiya's answer is right, but I needed sample in Kotlin...

For Kotlin:

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

Here Kotlin solution

Upvotes: 13

Priyanka Alachiya
Priyanka Alachiya

Reputation: 1726

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

Upvotes: 36

Related Questions