Sam Chen
Sam Chen

Reputation: 8857

Android Room Database Create Entity Object without Id

My entity class:

@Entity(tableName = "student")
data class Student(
    @PrimaryKey(autoGenerate = true)
    val id: Long,

    val name: String,
    val age: Int,
    val gpa: Double,
    val isSingle: Boolean
) 

The problem is, since the id is auto-generated by the Room database - means no matther what I put for the id into the constructor it will be overridden anyway, and because it is one of the parameter in the constructor, I have to give the id every time like this:

val student = Student(0L, "Sam", 27, 3.5, true)

How can I avoid making up the id so I can just put in the neccessary data like this:

val student = Student("Sam", 27, 3.5, true)

Upvotes: 12

Views: 2757

Answers (3)

jeprubio
jeprubio

Reputation: 18002

Don't place the id in the constructor:

@Entity(tableName = "student")
data class Student(
    val name: String,
    val age: Int,
    val gpa: Double,
    val isSingle: Boolean
) {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null
}

Upvotes: 13

Bahador Eslami
Bahador Eslami

Reputation: 392

If you want the auto increment id for your case just in your entity set the type of id to Int and for the id value parameter in your constructor use the null value and this handle the work for you .

Upvotes: 0

sergiy tykhonov
sergiy tykhonov

Reputation: 5103

How can I avoid making up the id

Just set default value to 0 (or null)

@Entity(tableName = "student")
data class Student(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0, <-- default value (or use null)

id is auto-generated by the Room database - means no matther what I put for the id into the constructor it will be overridden anyway

Not really like that. If you set id explicitly then this id will be used on insert.

Upvotes: 5

Related Questions