How to make primary key as autoincrement for Room

2019-01-31 05:32发布

问题:

I am creating a Entity(Room Persistence lib) class Food, where i want to make foodId as autoincrement.

@Entity
class Food(var foodName: String, var foodDesc: String, var protein: Double, var carbs: Double, var fat: Double)
{
    @PrimaryKey
    var foodId: Int = 0
    var calories: Double = 0.toDouble()
}

How can i set foodId an autoincrement field?

回答1:

You need to use the autoGenerate property

Your primary key annotation should be like this:

@PrimaryKey(autoGenerate = true)

Reference here



回答2:

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()
}


回答3:

add @PrimaryKey(autoGenerate = true)

@Entity
public class User {

    public User(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }


    @PrimaryKey(autoGenerate = true)
    private int id;

    @ColumnInfo(name = "full_name")
    private String name;

    @ColumnInfo(name = "phone")
    private String phone;

}

while storing data

 db.userDao().InsertAll(new User(0,sName,sPhone));

Put 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.



回答4:

For example, if you have a users entity you want to store, with fields (firstname, lastname , email) and you want autogenerated id, you do this.

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerated = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

Room will then autogenerate and auto-increment the id field.