How to make primary key as autoincrement for Room Persistence lib

前端 未结 8 1334
無奈伤痛
無奈伤痛 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:31

    Annotate your Entity class with the code below.

    In Java:

    @PrimaryKey(autoGenerate = true)
    private int id;
    

    In Kotlin:

    @PrimaryKey(autoGenerate = true)
    var id: Int
    

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

    0 讨论(0)
  • 2020-12-07 12:36

    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)
    }
    
    0 讨论(0)
提交回复
热议问题