How to make primary key as autoincrement for Room Persistence lib

前端 未结 8 1361
無奈伤痛
無奈伤痛 2020-12-07 11:55

I am creating an Entity (Room Persistence Library) class Food, where I want to make foodId as autoincrement.

@Entity
class Food(var foodName: Str         


        
8条回答
  •  被撕碎了的回忆
    2020-12-07 12:29

    This works for me:

    @Entity(tableName = "note_table")
    data class Note(
        @ColumnInfo(name="title") var title: String,
        @ColumnInfo(name="description") var description: String = "",
        @ColumnInfo(name="priority") var priority: Int,
        @PrimaryKey(autoGenerate = true) var id: Int = 0//last so that we don't have to pass an ID value or named arguments
    )
    

    Note that the id is last to avoid having to use named arguments when creating the entity, before inserting it into Room. Once it's been added to room, use the id when updating the entity.

提交回复
热议问题