How to make primary key as autoincrement for Room Persistence lib
You need to use the autoGenerate
property
Your primary key annotation should be like this:
@PrimaryKey(autoGenerate = true)
Reference for PrimaryKey.
You can add @PrimaryKey(autoGenerate = true)
like this:
@Entity
data class Food(
var foodName: String,
var foodDesc: String,
var protein: Double,
var carbs: Double,
var fat: Double
){
@PrimaryKey(autoGenerate = true)
var foodId: Int = 0 // or foodId: Int? = null
var calories: Double = 0.toDouble()
}
Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.
@Entity(tableName = "employments")
data class Employment(
@PrimaryKey(autoGenerate = true) val id: Long,
@ColumnInfo(name = "code") val code: String,
@ColumnInfo(name = "title") val name: String
){
constructor(code: String, name: String) : this(0, code, name)
}
add @PrimaryKey(autoGenerate = true)
@Entity
public class User {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "full_name")
private String name;
@ColumnInfo(name = "phone")
private String phone;
public User(){
}
//type-1
public User(String name, String phone) {
this.name = name;
this.phone = phone;
}
//type-2
public User(int id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
}
while storing data
//type-1
db.userDao().InsertAll(new User(sName,sPhone));
//type-2
db.userDao().InsertAll(new User(0,sName,sPhone));
type-1
If you are not passing value for primary key, by default it will 0 or null.
type-2
Put null or zero for the id while creating object (my case user object)
If the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.
If the field's type is Integer or Long (Object) (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.